225 lines
6.2 KiB
Go
225 lines
6.2 KiB
Go
package http
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"github.com/dusiburg/kotosoft-id/internal/handlers"
|
|
"github.com/dusiburg/kotosoft-id/internal/middleware"
|
|
"github.com/dusiburg/kotosoft-id/internal/models"
|
|
"github.com/dusiburg/kotosoft-id/internal/repositories"
|
|
"github.com/dusiburg/kotosoft-id/internal/services"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
func NewRouter(
|
|
auth *handlers.AuthHandler,
|
|
oauth *handlers.OAuthHandler,
|
|
consents *handlers.ConsentHandler,
|
|
positions *handlers.PositionsHandler,
|
|
citizenship *handlers.CitizenshipHandler,
|
|
svc *services.Service,
|
|
repo *repositories.OAuthRepository,
|
|
limiter *services.RateLimiter,
|
|
) *gin.Engine {
|
|
r := gin.Default()
|
|
r.Use(middleware.LoggingMiddleware())
|
|
r.Use(errorMiddleware())
|
|
|
|
o := r.Group("/oauth")
|
|
{
|
|
o.GET("/authorize", oauth.Authorize)
|
|
o.GET("/session/:token", oauth.GetSession)
|
|
o.POST("/session/login",
|
|
middleware.RateLimit(limiter, services.LoginRateLimit, middleware.LoginKeyFn),
|
|
oauth.SessionLogin,
|
|
)
|
|
o.POST("/session/attach", oauth.SessionAttach)
|
|
o.POST("/session/approve", oauth.SessionApprove)
|
|
o.POST("/token", oauth.Token)
|
|
o.POST("/revoke", oauth.Revoke)
|
|
|
|
o.POST("/introspect", positions.Introspect)
|
|
}
|
|
|
|
api := r.Group("/api/v1")
|
|
{
|
|
a := api.Group("/auth")
|
|
a.POST("/register",
|
|
middleware.RateLimit(limiter, services.RegisterRateLimit, middleware.IPKeyFn("register")),
|
|
auth.Register,
|
|
)
|
|
a.POST("/refresh", auth.Refresh)
|
|
|
|
me := api.Group("/me")
|
|
me.GET("", authMiddleware(svc, repo, "profile:read"), auth.Profile)
|
|
me.PATCH("", authMiddleware(svc, repo, "profile:edit"), auth.UpdateProfile)
|
|
me.DELETE("", authMiddleware(svc, repo, "profile:delete"), auth.DeleteProfile)
|
|
me.GET("/consents", authMiddleware(svc, repo, "profile:consent:read"), consents.GetUserConsents)
|
|
me.DELETE("/consent/:clientId", authMiddleware(svc, repo, "profile:consent:delete"), consents.RevokeAppAccess)
|
|
me.GET("/positions", authMiddleware(svc, repo, "profile:read"), positions.GetMyPositions)
|
|
me.GET("/citizenship", authMiddleware(svc, repo, "profile:read"), citizenship.GetCitizenshipApplicationByUserId)
|
|
me.POST("/citizenship", authMiddleware(svc, repo, "profile:edit"), citizenship.CreateCitizenshipApplication)
|
|
|
|
admin := api.Group("/admin", authMiddleware(svc, repo))
|
|
{
|
|
admin.PATCH("/citizenship/applications/:id", middleware.AdminOnly(), citizenship.ReviewCitizenshipApplication)
|
|
|
|
manage := admin.Group("", permissionMiddleware(svc, "positions.manage"))
|
|
{
|
|
manage.GET("/permissions", positions.ListPermissions)
|
|
manage.POST("/permissions", positions.CreatePermission)
|
|
manage.PUT("/permissions/:code", positions.UpdatePermission)
|
|
manage.DELETE("/permissions/:code", positions.DeletePermission)
|
|
|
|
manage.GET("/positions", positions.ListPositions)
|
|
manage.POST("/positions", positions.UpsertPosition)
|
|
manage.PUT("/positions/:code", positions.UpdatePosition)
|
|
manage.DELETE("/positions/:code", positions.DeletePosition)
|
|
manage.POST("/positions/:code/permissions", positions.AddPermissionToPosition)
|
|
manage.DELETE("/positions/:code/permissions/:permissionCode", positions.RemovePermissionFromPosition)
|
|
}
|
|
|
|
usersRead := admin.Group("", permissionAnyMiddleware(svc, "positions.assign", "positions.revoke"))
|
|
{
|
|
usersRead.GET("/users", positions.ListUsersWithPositions)
|
|
}
|
|
|
|
assign := admin.Group("", permissionMiddleware(svc, "positions.assign"))
|
|
{
|
|
assign.POST("/users/:userId/positions", positions.AssignPosition)
|
|
}
|
|
|
|
revoke := admin.Group("", permissionMiddleware(svc, "positions.revoke"))
|
|
{
|
|
revoke.DELETE("/users/:userId/positions/:code", positions.RevokePosition)
|
|
}
|
|
}
|
|
}
|
|
|
|
return r
|
|
}
|
|
|
|
func permissionAnyMiddleware(svc *services.Service, requiredPermissions ...string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
userID, ok := UserIDFromContext(c)
|
|
if !ok {
|
|
c.Error(models.ErrUnauthorized)
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
for _, permission := range requiredPermissions {
|
|
allowed, err := svc.UserHasPermission(c.Request.Context(), userID, permission)
|
|
if err != nil {
|
|
c.Error(models.ErrInternal)
|
|
c.Abort()
|
|
return
|
|
}
|
|
if allowed {
|
|
c.Next()
|
|
return
|
|
}
|
|
}
|
|
|
|
c.Error(models.ErrForbidden.WithMessage("Missing required permissions"))
|
|
c.Abort()
|
|
}
|
|
}
|
|
|
|
func permissionMiddleware(svc *services.Service, requiredPermission string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
userID, ok := UserIDFromContext(c)
|
|
if !ok {
|
|
c.Error(models.ErrUnauthorized)
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
allowed, err := svc.UserHasPermission(c.Request.Context(), userID, requiredPermission)
|
|
if err != nil {
|
|
c.Error(models.ErrInternal)
|
|
c.Abort()
|
|
return
|
|
}
|
|
if !allowed {
|
|
c.Error(models.ErrForbidden.WithMessage("Missing required permission: " + requiredPermission))
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func authMiddleware(svc *services.Service, repo *repositories.OAuthRepository, requiredScopes ...string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
token, ok := bearerToken(c)
|
|
if !ok {
|
|
c.Error(models.ErrUnauthorized)
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
info, err := svc.ValidateAccessToken(c.Request.Context(), token)
|
|
if err != nil {
|
|
c.Error(models.ErrUnauthorized)
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
if len(requiredScopes) > 0 && !services.ScopesContain(info.Scopes, requiredScopes) {
|
|
c.Error(models.ErrInsufficientScope)
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
if _, err := repo.GetOAuthClientByID(c.Request.Context(), info.ClientID); err != nil {
|
|
c.Error(models.ErrForbidden)
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
user, err := svc.GetUserByID(c.Request.Context(), info.UserID)
|
|
if err != nil {
|
|
c.Error(models.ErrUnauthorized)
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Set("user_id", info.UserID)
|
|
c.Set("is_admin", user.IsAdmin)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func errorMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
c.Next()
|
|
if len(c.Errors) == 0 || c.Writer.Written() {
|
|
return
|
|
}
|
|
|
|
err := c.Errors.Last().Err
|
|
if apiErr, ok := err.(*models.APIError); ok {
|
|
c.JSON(apiErr.Code, apiErr)
|
|
return
|
|
}
|
|
|
|
c.JSON(500, models.ErrInternal)
|
|
}
|
|
}
|
|
|
|
func bearerToken(c *gin.Context) (string, bool) {
|
|
return strings.CutPrefix(c.GetHeader("Authorization"), "Bearer ")
|
|
}
|
|
|
|
func UserIDFromContext(c *gin.Context) (uuid.UUID, bool) {
|
|
v, ok := c.Get("user_id")
|
|
if !ok {
|
|
return uuid.Nil, false
|
|
}
|
|
id, ok := v.(uuid.UUID)
|
|
return id, ok
|
|
}
|