golang-lib/web/auth/lib_user.go

62 lines
1.3 KiB
Go
Raw Normal View History

2021-06-01 10:51:35 +02:00
package auth
import (
"errors"
"net/http"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"gorm.io/gorm"
2023-10-23 21:40:10 +02:00
"codeberg.org/genofire/golang-lib/web"
2021-06-01 10:51:35 +02:00
)
// IsLoginWithUserID get UserID of session in golang-gin
func IsLoginWithUserID(c *gin.Context) (uuid.UUID, bool) {
2021-06-01 10:51:35 +02:00
session := sessions.Default(c)
v := session.Get("user_id")
if v == nil {
return uuid.Nil, false
}
id := uuid.MustParse(v.(string))
return id, true
}
// GetCurrentUserID get UserID of session in golang-gin
func GetCurrentUserID(c *gin.Context) (uuid.UUID, bool) {
id, ok := IsLoginWithUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, web.HTTPError{
Message: ErrAPINoSession.Error(),
})
}
return id, ok
}
2021-06-01 18:44:09 +02:00
// GetCurrentUser get User of session from database in golang-gin
2021-06-01 10:51:35 +02:00
func GetCurrentUser(c *gin.Context, ws *web.Service) (*User, bool) {
id, ok := GetCurrentUserID(c)
if !ok {
return nil, false
}
d := &User{ID: id}
if err := ws.DB.First(d).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.JSON(http.StatusUnauthorized, web.HTTPError{
2021-07-22 18:16:05 +02:00
Message: ErrAPIUserNotFound.Error(),
2021-06-01 10:51:35 +02:00
Error: err.Error(),
})
return nil, false
}
c.JSON(http.StatusInternalServerError, web.HTTPError{
2021-07-22 18:16:05 +02:00
Message: web.ErrAPIInternalDatabase.Error(),
2021-06-01 10:51:35 +02:00
Error: err.Error(),
})
return nil, false
}
return d, true
}