Skip to content

Commit

Permalink
Create new user on successful login
Browse files Browse the repository at this point in the history
  • Loading branch information
Aadesh-Baral committed Aug 24, 2022
1 parent d2a34c1 commit bf6475e
Show file tree
Hide file tree
Showing 5 changed files with 146 additions and 2 deletions.
12 changes: 11 additions & 1 deletion backend/server/api/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,18 @@ func (server *Server) callback(ctx *gin.Context) {
return
}

// Create/update user in database and return logged in user details.
loggedInUserResponse, err := services.LoginUser(server.query, &user_info)
if err != nil {
ctx.JSON(
http.StatusInternalServerError,
gin.H{"error": "error logging in"},
)
log.Errorf(ctx, "error logging in: %v", err)
return
}
ctx.JSON(
http.StatusOK,
&user_info,
loggedInUserResponse,
)
}
5 changes: 4 additions & 1 deletion backend/server/api/server.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package api

import (
db "github.com/baato/before-after/db/sqlc"
"github.com/baato/before-after/util"
"github.com/gin-gonic/gin"
)
Expand All @@ -19,12 +20,14 @@ var dispatcher = NewDispatcher(jobQueue, maxWorkers)

type Server struct {
router *gin.Engine
query *db.Queries
config *util.Config
}

func NewServer(config *util.Config) *Server {
func NewServer(query *db.Queries, config *util.Config) *Server {
server := &Server{
config: config,
query: query,
}

server.setupRouter()
Expand Down
36 changes: 36 additions & 0 deletions backend/server/serializers/users_serializers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package serializer

import (
"time"

db "github.com/baato/before-after/db/sqlc"
)

type UserResponse struct {
ID int32 `json:"id"`
Username string `json:"username"`
PictureURL string `json:"picture_url"`
CreatedAt time.Time `json:"created_at"`
Role int32 `json:"role"`
EmailAddress string `json:"email_address"`
IsEmailVerified bool `json:"is_email_verified"`
}

func NewUserResponse(user db.User) UserResponse {
return UserResponse{
ID: user.ID,
Username: user.Username,
PictureURL: user.PictureUrl.String,
CreatedAt: user.CreatedAt,
Role: user.Role,
EmailAddress: user.EmailAddress.String,
IsEmailVerified: user.IsEmailVerified.Bool,
}
}

type UpdateUserRequest struct {
ID int32 `json:"id"`
Role int32 `json:"role"`
EmailAddress string `json:"email_address"`
IsEmailVerified bool `json:"is_email_verified"`
}
65 changes: 65 additions & 0 deletions backend/server/services/auth_service.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
package services

import (
"context"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"time"

db "github.com/baato/before-after/db/sqlc"
serializer "github.com/baato/before-after/serializers"
"github.com/baato/before-after/util"
)

type OSMResponse struct {
Expand All @@ -20,6 +26,12 @@ type Picture struct {
Url string `json:"href"`
}

var config util.Config

func init() {
config, _ = util.LoadConfig(".")
}

// Get user details from OSM API
func GetOSMUser(token string) (UserInfo, error) {
client := &http.Client{}
Expand All @@ -44,3 +56,56 @@ func GetOSMUser(token string) (UserInfo, error) {
}
return userinfo.User, nil
}

// Create a new user in db if user not found else updates existing user and returns user
func LoginUser(query *db.Queries, userinfo *UserInfo) (serializer.UserResponse, error) {

// Check if user exists in db
_, getErr := query.GetUser(context.Background(), userinfo.ID)
var user db.User
var err error
if getErr == nil {
// User exists in db, so update user
user, err = updateUser(query, userinfo)
} else {
// User not found in db, so create user
user, err = createUser(query, userinfo)
}
if err != nil {
return serializer.UserResponse{}, err
} else {
userResponse := serializer.NewUserResponse(user)
return userResponse, nil
}

}

// Generates session token with username and secret key
func GenerateSessionToken(userid int32) string {
maker, err := NewJWTMaker(config.AppSecret)
if err != nil {
panic(err)
}
token, _, err := maker.CreateToken(userid, time.Hour)
if err != nil {
panic(err)
}
return token
}

// Verifies token and returns username
func VerifySessionToken(token string, userid int32) (int32, bool) {
maker, err := NewJWTMaker(config.AppSecret)
if err != nil {
panic(err)
}
payload, err := maker.VerifyToken(token)
if err != nil {
panic(err)
}
if payload.UserID == userid {
return payload.UserID, true
} else {
return 0, false
}
}
30 changes: 30 additions & 0 deletions backend/server/services/user_service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package services

import (
"context"
"database/sql"

db "github.com/baato/before-after/db/sqlc"
)

// Create a new user in db
func createUser(query *db.Queries, userinfo *UserInfo) (db.User, error) {
arg := db.CreateUserParams{
ID: userinfo.ID,
Username: userinfo.DisplayName,
PictureUrl: sql.NullString{String: userinfo.Picture.Url, Valid: true},
}
user, err := query.CreateUser(context.Background(), arg)
return user, err
}

// Updates existing user in db
func updateUser(query *db.Queries, userinfo *UserInfo) (db.User, error) {
arg := db.UpdateUserParams{
ID: userinfo.ID,
Username: userinfo.DisplayName,
PictureUrl: sql.NullString{String: userinfo.Picture.Url, Valid: true},
}
user, err := query.UpdateUser(context.Background(), arg)
return user, err
}

0 comments on commit bf6475e

Please sign in to comment.