51 lines
1.6 KiB
Go
51 lines
1.6 KiB
Go
package services
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.secnex.io/secnex/oauth2-api/models"
|
|
"git.secnex.io/secnex/oauth2-api/repositories"
|
|
"git.secnex.io/secnex/oauth2-api/utils"
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type AuthorizeResponse struct {
|
|
Code string `json:"code"`
|
|
State string `json:"state"`
|
|
}
|
|
|
|
func Authorize(userID, clientID, redirectURI, responseType, scope, state string) *utils.HTTPResponse {
|
|
application, err := repositories.GetApplicationByClientID(clientID)
|
|
if err != nil {
|
|
return utils.NewHTTPResponse(http.StatusUnauthorized, &fiber.Map{"error": "Application not found"}, "", nil, nil)
|
|
}
|
|
if application.ExpiresAt.Before(time.Now().UTC()) {
|
|
return utils.NewHTTPResponse(http.StatusUnauthorized, &fiber.Map{"error": "Application expired"}, "", nil, nil)
|
|
}
|
|
authorizationID := uuid.New()
|
|
authorizationCode := utils.GenerateRandomString(32)
|
|
authorization := &models.Authorization{
|
|
ID: authorizationID,
|
|
Code: authorizationCode,
|
|
ClientID: application.ID,
|
|
UserID: uuid.MustParse(userID),
|
|
}
|
|
if err := repositories.CreateAuthorization(authorization); err != nil {
|
|
return utils.NewHTTPResponse(http.StatusInternalServerError, &fiber.Map{"error": "Failed to create authorization"}, "", nil, nil)
|
|
}
|
|
|
|
authorizationCodeString := fmt.Sprintf("%s:%s", authorizationID.String(), authorizationCode)
|
|
authorizationCodeBase64 := base64.StdEncoding.EncodeToString([]byte(authorizationCodeString))
|
|
|
|
response := AuthorizeResponse{
|
|
Code: authorizationCodeBase64,
|
|
State: state,
|
|
}
|
|
|
|
return utils.NewHTTPResponse(http.StatusOK, &fiber.Map{"response": response}, "", nil, nil)
|
|
}
|