package api import ( "context" "errors" "net/http" "strings" "time" "mediarr/auth" "mediarr/identity" ) const sessionCookieName = "mediarr_session" type contextKey int const ( userContextKey contextKey = iota tokenContextKey ) type loginRequest struct { Login string `json:"login"` Password string `json:"password"` Label string `json:"label,omitempty"` } type loginResponse struct { Token string `json:"token"` Principal principalDTO `json:"principal"` Account accountDTO `json:"account"` } type createUserRequest struct { Login string `json:"login"` Password string `json:"password"` Role string `json:"role,omitempty"` } type userDTO struct { Principal principalDTO `json:"principal"` Account accountDTO `json:"account"` } type principalDTO struct { ID string `json:"id"` Kind string `json:"kind"` Name string `json:"name"` Status string `json:"status"` CreatedAt int64 `json:"created_at"` Groups []groupDTO `json:"groups"` } type groupDTO struct { ID string `json:"id"` Name string `json:"name"` Status string `json:"status"` Role string `json:"role"` } type accountDTO struct { Login string `json:"login"` State string `json:"state"` MustChangePassword bool `json:"must_change_password"` LastLoginAt *int64 `json:"last_login_at,omitempty"` } func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { var request loginRequest if err := decodeJSON(w, r, &request); err != nil { writeErrorFor(w, err) return } user, err := s.node.Auth().Authenticate(r.Context(), request.Login, request.Password) if err != nil { writeErrorFor(w, err) return } _, token, err := s.node.Auth().CreateSession(r.Context(), auth.CreateSessionParams{ PrincipalID: user.Principal.ID, Kind: "web", Label: request.Label, UserAgent: r.UserAgent(), }) if err != nil { writeErrorFor(w, err) return } http.SetCookie(w, &http.Cookie{ Name: sessionCookieName, Value: token, Path: "/", MaxAge: int((30 * 24 * time.Hour).Seconds()), HttpOnly: true, SameSite: http.SameSiteLaxMode, }) dto := userDTOFrom(user) writeJSON(w, http.StatusOK, loginResponse{ Token: token, Principal: dto.Principal, Account: dto.Account, }) } func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) { token := currentToken(r) if token != "" { if err := s.node.Auth().RevokeSessionByToken(r.Context(), token); err != nil && !errors.Is(err, auth.ErrInvalidSession) { writeErrorFor(w, err) return } } http.SetCookie(w, &http.Cookie{ Name: sessionCookieName, Value: "", Path: "/", MaxAge: -1, HttpOnly: true, SameSite: http.SameSiteLaxMode, }) w.WriteHeader(http.StatusNoContent) } func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) { user := currentUser(r) if user == nil { writeError(w, http.StatusUnauthorized, auth.ErrInvalidSession.Error()) return } writeJSON(w, http.StatusOK, userDTOFrom(user)) } func (s *Server) handleCreateUser(w http.ResponseWriter, r *http.Request) { var request createUserRequest if err := decodeJSON(w, r, &request); err != nil { writeErrorFor(w, err) return } role := request.Role if role == "" { role = identity.RoleMember } created, err := s.node.Auth().CreateUser(r.Context(), auth.CreateUserParams{ Login: request.Login, Password: request.Password, Role: role, }) if err != nil { writeErrorFor(w, err) return } writeJSON(w, http.StatusCreated, userDTOFrom(created)) } func (s *Server) requireAuth(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token := extractToken(r) if token == "" { writeError(w, http.StatusUnauthorized, auth.ErrInvalidSession.Error()) return } _, user, err := s.node.Auth().ValidateSession(r.Context(), token) if err != nil { writeErrorFor(w, err) return } ctx := context.WithValue(r.Context(), userContextKey, user) ctx = context.WithValue(ctx, tokenContextKey, token) next.ServeHTTP(w, r.WithContext(ctx)) }) } func (s *Server) requireAdmin(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user := currentUser(r) if user == nil || !isAdmin(user) { writeError(w, http.StatusForbidden, "droits administrateur requis") return } next.ServeHTTP(w, r) }) } func extractToken(r *http.Request) string { if header := r.Header.Get("Authorization"); header != "" { if strings.HasPrefix(strings.ToLower(header), "bearer ") { return strings.TrimSpace(header[len("bearer "):]) } return "" } cookie, err := r.Cookie(sessionCookieName) if err != nil { return "" } return cookie.Value } func currentUser(r *http.Request) *auth.AuthenticatedUser { user, _ := r.Context().Value(userContextKey).(*auth.AuthenticatedUser) return user } func currentToken(r *http.Request) string { token, _ := r.Context().Value(tokenContextKey).(string) return token } func isAdmin(user *auth.AuthenticatedUser) bool { for _, group := range user.Principal.Groups { if group.Role == identity.RoleAdmin || group.Name == "admins" { return true } } return false } func userDTOFrom(user *auth.AuthenticatedUser) userDTO { groups := make([]groupDTO, 0, len(user.Principal.Groups)) for _, group := range user.Principal.Groups { groups = append(groups, groupDTO{ ID: group.ID.String(), Name: group.Name, Status: group.Status, Role: group.Role, }) } var lastLoginAt *int64 if user.Account.LastLoginAt.Valid { value := user.Account.LastLoginAt.Int64 lastLoginAt = &value } return userDTO{ Principal: principalDTO{ ID: user.Principal.ID.String(), Kind: user.Principal.Kind, Name: user.Principal.Name, Status: user.Principal.Status, CreatedAt: user.Principal.CreatedAt, Groups: groups, }, Account: accountDTO{ Login: user.Account.Login, State: user.Account.State, MustChangePassword: user.Account.MustChangePassword, LastLoginAt: lastLoginAt, }, } }