Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions apps/jan-api-gateway/application/app/domain/user/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ func (s *UserService) RegisterUser(ctx context.Context, user *User) (*User, erro
return user, nil
}

func (s *UserService) UpdateUser(ctx context.Context, user *User) (*User, error) {
if err := s.userrepo.Update(ctx, user); err != nil {
return nil, err
}
return user, nil
}

func (s *UserService) FindByEmail(ctx context.Context, email string) (*User, error) {
users, err := s.userrepo.FindByFilter(ctx, UserFilter{
Email: &email,
Expand Down
2 changes: 2 additions & 0 deletions apps/jan-api-gateway/application/app/domain/user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type User struct {
Enabled bool
PublicID string
CreatedAt time.Time
IsGuest bool
}

type UserFilter struct {
Expand All @@ -27,6 +28,7 @@ type UserFilter struct {

type UserRepository interface {
Create(ctx context.Context, u *User) error
Update(ctx context.Context, u *User) error
FindFirst(ctx context.Context, filter UserFilter) (*User, error)
FindByFilter(ctx context.Context, filter UserFilter, p *query.Pagination) ([]*User, error)
FindByID(ctx context.Context, id uint) (*User, error)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type User struct {
Enabled bool
Organizations []OrganizationMember `gorm:"foreignKey:UserID"`
Projects []ProjectMember `gorm:"foreignKey:UserID"`
IsGuest bool
}

func NewSchemaUser(u *user.User) *User {
Expand All @@ -28,6 +29,7 @@ func NewSchemaUser(u *user.User) *User {
Email: u.Email,
Enabled: u.Enabled,
PublicID: u.PublicID,
IsGuest: u.IsGuest,
}
}

Expand All @@ -39,5 +41,6 @@ func (u *User) EtoD() *user.User {
Enabled: u.Enabled,
PublicID: u.PublicID,
CreatedAt: u.CreatedAt,
IsGuest: u.IsGuest,
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,9 @@ func (repo *UserGormRepository) applyFilter(query *gormgen.Query, sql gormgen.IU
}
return sql
}

func (r *UserGormRepository) Update(ctx context.Context, u *domain.User) error {
user := dbschema.NewSchemaUser(u)
query := r.db.GetQuery(ctx)
return query.User.WithContext(ctx).Save(user)
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"menlo.ai/jan-api-gateway/app/domain/user"
"menlo.ai/jan-api-gateway/app/interfaces/http/responses"
"menlo.ai/jan-api-gateway/app/interfaces/http/routes/v1/auth/google"
"menlo.ai/jan-api-gateway/config/environment_variables"
)

type AuthRoute struct {
Expand Down Expand Up @@ -117,34 +116,7 @@ func (authRoute *AuthRoute) Logout(reqCtx *gin.Context) {
// @Router /v1/auth/refresh-token [get]
func (authRoute *AuthRoute) RefreshToken(reqCtx *gin.Context) {
ctx := reqCtx.Request.Context()
refreshTokenString, err := reqCtx.Cookie(auth.RefreshTokenKey)
if err != nil {
reqCtx.AbortWithStatusJSON(http.StatusUnauthorized, responses.ErrorResponse{
Code: "b95e8123-2590-48ed-bbad-e02d88464513",
Error: err.Error(),
})
return
}

token, err := jwt.ParseWithClaims(refreshTokenString, &auth.UserClaim{}, func(token *jwt.Token) (interface{}, error) {
return environment_variables.EnvironmentVariables.JWT_SECRET, nil
})
if err != nil {
reqCtx.AbortWithStatusJSON(http.StatusUnauthorized, responses.ErrorResponse{
Code: "7c7b8a48-311c-4beb-a2a1-1c13a87610bb",
Error: err.Error(),
})
return
}

if !token.Valid {
reqCtx.AbortWithStatusJSON(http.StatusUnauthorized, responses.ErrorResponse{
Code: "ec5fa88c-78bb-462a-ab90-b046f269d5eb",
})
return
}

userClaim, ok := token.Claims.(*auth.UserClaim)
userClaim, ok := auth.GetUserClaimFromRefreshToken(reqCtx)
if !ok {
reqCtx.AbortWithStatusJSON(http.StatusUnauthorized, responses.ErrorResponse{
Code: "c2019018-b71c-4f13-8ac6-854fbd61c9dd",
Expand Down Expand Up @@ -181,7 +153,7 @@ func (authRoute *AuthRoute) RefreshToken(reqCtx *gin.Context) {
}

refreshTokenExp := time.Now().Add(7 * 24 * time.Hour)
refreshTokenString, err = auth.CreateJwtSignedString(auth.UserClaim{
refreshTokenString, err := auth.CreateJwtSignedString(auth.UserClaim{
Email: userClaim.Email,
Name: userClaim.Name,
ID: userClaim.ID,
Expand Down Expand Up @@ -233,8 +205,9 @@ func (authRoute *AuthRoute) GuestLogin(reqCtx *gin.Context) {
randomStr := strings.ToUpper(uuid.New().String())
user, err := authRoute.authService.RegisterUser(ctx, &user.User{
Name: fmt.Sprintf("Jan-%s", randomStr),
Email: fmt.Sprintf("Jan-%[email protected]", randomStr),
Email: fmt.Sprintf("Jan-%s@guest.jan.ai", randomStr),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we get shorter email ( like get first 12 char )
And if guest user can register with organization and project in RegisterUser flow. is that fine?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The organization and project will be created during user registration (OpenAI implements it this way).
There is no need to assign an organization ID from the admin endpoints they provide:
curl https://api.openai.com/v1/organization/projects?after=proj_abc&limit=20&include_archived=false
-> We can revert this change when we have a back office UI.

Enabled: true,
IsGuest: true,
})
if err != nil {
reqCtx.AbortWithStatusJSON(http.StatusOK, responses.ErrorResponse{
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's note related but the http.StatusOK with response object

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ func generateState() (string, error) {
// @Failure 500 {object} responses.ErrorResponse "Internal Server Error"
// @Router /v1/auth/google/callback [post]
func (googleAuthAPI *GoogleAuthAPI) HandleGoogleCallback(reqCtx *gin.Context) {
ctx := reqCtx.Request.Context()
var req GoogleCallbackRequest
if err := reqCtx.ShouldBindJSON(&req); err != nil {
reqCtx.AbortWithStatusJSON(http.StatusBadRequest, responses.ErrorResponse{
Expand Down Expand Up @@ -160,7 +161,40 @@ func (googleAuthAPI *GoogleAuthAPI) HandleGoogleCallback(reqCtx *gin.Context) {
return
}
if exists == nil {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should move the logic below to the use case if it's reusable when integrating a new OIDC provider, but leave it as is for now, since premature optimization is the root of all evil.

exists, err = googleAuthAPI.userService.RegisterUser(reqCtx.Request.Context(), &user.User{
exists, err = func() (*user.User, error) {
userClaim, ok := auth.GetUserClaimFromRefreshToken(reqCtx)
if !ok {
return nil, nil
}
user, err := googleAuthAPI.userService.FindByEmail(ctx, userClaim.Email)
if err != nil {
return nil, err
}
if user == nil {
return nil, nil
}
if user.IsGuest {
user.IsGuest = false
user.Name = claims.Name
user.Email = claims.Email
exists, err = googleAuthAPI.userService.UpdateUser(ctx, user)
if err != nil {
return nil, err
}
return exists, nil
}
return nil, nil
}()
if err != nil {
reqCtx.AbortWithStatusJSON(http.StatusInternalServerError, responses.ErrorResponse{
Code: "f7c545df-bdcd-4e6a-843e-9699f0239552",
ErrorInstance: err,
})
return
}
}
if exists == nil {
exists, err = googleAuthAPI.authService.RegisterUser(ctx, &user.User{
Name: claims.Name,
Email: claims.Email,
Enabled: true,
Expand All @@ -173,7 +207,6 @@ func (googleAuthAPI *GoogleAuthAPI) HandleGoogleCallback(reqCtx *gin.Context) {
return
}
}

accessTokenExp := time.Now().Add(auth.AccessTokenExpirationDuration)
accessTokenString, err := auth.CreateJwtSignedString(auth.UserClaim{
Email: exists.Email,
Expand Down
Loading