openscore/controllers/base.go

98 lines
1.9 KiB
Go
Raw Normal View History

2022-07-27 20:01:53 +08:00
// Copyright 2022 The OpenCT Authors. All Rights Reserved.
2021-07-24 23:48:03 +08:00
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
2022-07-27 20:26:37 +08:00
"encoding/gob"
2022-08-10 12:07:33 +08:00
"errors"
2021-07-24 23:48:03 +08:00
2022-07-27 20:01:53 +08:00
"github.com/astaxie/beego"
2022-08-10 12:07:33 +08:00
auth "github.com/casdoor/casdoor-go-sdk/casdoorsdk"
2021-07-24 23:48:03 +08:00
)
type ApiController struct {
beego.Controller
}
2022-07-27 20:26:37 +08:00
func init() {
gob.Register(auth.Claims{})
2021-07-28 23:00:37 +08:00
}
2022-07-27 20:26:37 +08:00
func GetUserName(user *auth.User) string {
if user == nil {
return ""
}
2022-07-27 20:01:53 +08:00
2022-07-27 20:26:37 +08:00
return user.Name
2021-09-06 14:01:21 +08:00
}
2021-08-24 12:08:09 +08:00
2022-07-27 20:26:37 +08:00
func (c *ApiController) GetSessionClaims() *auth.Claims {
2021-07-24 23:48:03 +08:00
s := c.GetSession("user")
if s == nil {
return nil
}
2022-07-27 20:26:37 +08:00
claims := s.(auth.Claims)
return &claims
}
func (c *ApiController) SetSessionClaims(claims *auth.Claims) {
if claims == nil {
c.DelSession("user")
return
2021-07-24 23:48:03 +08:00
}
2022-07-27 20:26:37 +08:00
c.SetSession("user", *claims)
2021-07-24 23:48:03 +08:00
}
2022-07-27 20:26:37 +08:00
func (c *ApiController) GetSessionUser() *auth.User {
claims := c.GetSessionClaims()
2021-07-24 23:48:03 +08:00
if claims == nil {
2022-07-27 20:26:37 +08:00
return nil
}
return &claims.User
}
func (c *ApiController) SetSessionUser(user *auth.User) {
if user == nil {
2021-07-24 23:48:03 +08:00
c.DelSession("user")
return
}
2022-07-27 20:26:37 +08:00
claims := c.GetSessionClaims()
if claims != nil {
claims.User = *user
c.SetSessionClaims(claims)
}
2021-07-24 23:48:03 +08:00
}
func (c *ApiController) GetSessionUsername() string {
2022-07-27 20:26:37 +08:00
user := c.GetSessionUser()
if user == nil {
2021-07-24 23:48:03 +08:00
return ""
}
2022-07-27 20:26:37 +08:00
return GetUserName(user)
2021-07-24 23:48:03 +08:00
}
2022-08-10 12:07:33 +08:00
func (c *ApiController) GetSessionUserId() (int64, error) {
id, ok := c.Controller.GetSession("userId").(int64)
if !ok {
return 0, errors.New("not login")
}
return id, nil
}