sessions/internal/domain/session.go
Dawid Wysokiński 786cc60e38
All checks were successful
continuous-integration/drone/push Build is passing
feat: add a new REST endpoint - GET /api/v1/user/sessions/:server (#14)
Reviewed-on: #14
2022-11-25 05:55:31 +00:00

103 lines
1.8 KiB
Go

package domain
import (
"encoding/base64"
"fmt"
"time"
)
const (
serverMaxLen = 10
)
type Session struct {
ID int64
UserID int64
ServerKey string
SID string
CreatedAt time.Time
UpdatedAt time.Time
}
type CreateSessionParams struct {
userID int64
serverKey string
sid string
}
func NewCreateSessionParams(serverKey, sid string, userID int64) (CreateSessionParams, error) {
if serverKey == "" {
return CreateSessionParams{}, ValidationError{
Field: "ServerKey",
Err: ErrRequired,
}
}
if len(serverKey) > serverMaxLen {
return CreateSessionParams{}, ValidationError{
Field: "ServerKey",
Err: MaxLengthError{
Max: serverMaxLen,
},
}
}
if sid == "" {
return CreateSessionParams{}, ValidationError{
Field: "SID",
Err: ErrRequired,
}
}
if !isBase64(sid) {
return CreateSessionParams{}, ValidationError{
Field: "SID",
Err: ErrBase64,
}
}
if userID < userIDMin {
return CreateSessionParams{}, ValidationError{
Field: "UserID",
Err: MinError{
Min: userIDMin,
},
}
}
return CreateSessionParams{userID: userID, serverKey: serverKey, sid: sid}, nil
}
func (c CreateSessionParams) UserID() int64 {
return c.userID
}
func (c CreateSessionParams) ServerKey() string {
return c.serverKey
}
func (c CreateSessionParams) SID() string {
return c.sid
}
func isBase64(s string) bool {
_, err := base64.StdEncoding.DecodeString(s)
return err == nil
}
type SessionNotFoundError struct {
ServerKey string
}
func (e SessionNotFoundError) Error() string {
return fmt.Sprintf("session (ServerKey=%s) not found", e.ServerKey)
}
func (e SessionNotFoundError) UserError() string {
return e.Error()
}
func (e SessionNotFoundError) Code() ErrorCode {
return ErrorCodeEntityNotFound
}