WASAPhoto/service/api/authorization/auth-bearer.go

62 lines
1.3 KiB
Go
Raw Normal View History

2022-11-18 13:05:40 +01:00
package authorization
import (
"errors"
"strings"
2022-11-18 17:18:46 +01:00
"github.com/notherealmarco/WASAPhoto/service/api/reqcontext"
2022-11-18 13:05:40 +01:00
"github.com/notherealmarco/WASAPhoto/service/database"
)
type BearerAuth struct {
token string
}
func (b *BearerAuth) GetType() string {
return "Bearer"
}
func BuildBearer(header string) (*BearerAuth, error) {
if header == "" {
return nil, errors.New("missing authorization header")
}
if header == "Bearer" {
return nil, errors.New("missing token")
}
if !strings.HasPrefix(header, "Bearer ") {
return nil, errors.New("invalid authorization header")
}
return &BearerAuth{token: header[7:]}, nil
}
func (b *BearerAuth) GetToken() string {
return b.token
}
func (b *BearerAuth) Authorized(db database.AppDatabase) (bool, error) {
// this is the way we manage authorization, the bearer token is the user id
state, err := db.UserExists(b.token)
if err != nil {
return false, err
}
return state, nil
}
2022-11-18 17:18:46 +01:00
func (b *BearerAuth) UserAuthorized(db database.AppDatabase, uid string) (reqcontext.AuthStatus, error) {
2022-11-18 13:05:40 +01:00
if b.token == uid {
2022-11-18 17:18:46 +01:00
auth, err := b.Authorized(db)
if err != nil {
return -1, err
}
if auth {
return reqcontext.AUTHORIZED, nil
} else {
return reqcontext.UNAUTHORIZED, nil
}
2022-11-18 13:05:40 +01:00
}
2022-11-18 17:18:46 +01:00
return reqcontext.FORBIDDEN, nil
2022-11-18 13:05:40 +01:00
}