How to use ToJSON method of logger Package

Best Gauge code snippet using logger.ToJSON

authentication.go

Source:authentication.go Github

copy

Full Screen

...19 accessToken, err := ah.authService.GenerateAccessToken(&user)20 if err != nil {21 ah.logger.Error("unable to generate access token", "error", err)22 w.WriteHeader(http.StatusInternalServerError)23 // data.ToJSON(&GenericError{Error: err.Error()}, w)24 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Unable to generate access token.Please try again later"}, w)25 return26 }27 w.WriteHeader(http.StatusOK)28 // data.ToJSON(&TokenResponse{AccessToken: accessToken}, w)29 utils.ToJSON(&response.GenericResponse{30 Status: true,31 Message: "Successfully generated new access token",32 Data: &response.TokenResponse{AccessToken: accessToken},33 }, w)34}35// Greet request greet request36func (ah *AuthenticationHandler) Greet(w http.ResponseWriter, r *http.Request) {37 w.Header().Set("Content-Type", "application/json")38 userID := r.Context().Value(UserIDKey{}).(string)39 w.WriteHeader(http.StatusOK)40 // w.Write([]byte("hello, " + userID))41 utils.ToJSON(&response.GenericResponse{42 Status: true,43 Message: "hello," + userID,44 }, w)45}46// GeneratePassResetCode generate a new secret code to reset password.47func (ah *AuthenticationHandler) GeneratePassResetCode(w http.ResponseWriter, r *http.Request) {48 w.Header().Set("Content-Type", "application/json")49 userID := r.Context().Value(UserIDKey{}).(string)50 user, err := ah.repo.GetUserByID(context.Background(), userID)51 if err != nil {52 ah.logger.Error("unable to get user to generate secret code for password reset", "error", err)53 w.WriteHeader(http.StatusInternalServerError)54 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Unable to send password reset code. Please try again later"}, w)55 return56 }57 // Send verification mail58 from := "ibrodex@gmail.com"59 to := []string{user.Email}60 subject := "Password Reset for Bookite"61 mailType := service.PassReset62 mailData := &service.MailData{63 Username: user.Username,64 Code: utils.GenerateRandomString(8),65 }66 mailReq := ah.mailService.NewMail(from, to, subject, mailType, mailData)67 err = ah.mailService.SendMail(mailReq)68 if err != nil {69 ah.logger.Error("unable to send mail", "error", err)70 w.WriteHeader(http.StatusInternalServerError)71 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Unable to send password reset code. Please try again later"}, w)72 return73 }74 // store the password reset code to db75 verificationData := &data.VerificationData{76 Email: user.Email,77 Code: mailData.Code,78 Type: data.PassReset,79 ExpiresAt: time.Now().Add(time.Minute * time.Duration(ah.configs.PassResetCodeExpiration)),80 }81 err = ah.repo.StoreVerificationData(context.Background(), verificationData)82 if err != nil {83 ah.logger.Error("unable to store password reset verification data", "error", err)84 w.WriteHeader(http.StatusInternalServerError)85 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Unable to send password reset code. Please try again later"}, w)86 return87 }88 ah.logger.Debug("successfully mailed password reset code")89 w.WriteHeader(http.StatusOK)90 utils.ToJSON(&response.GenericResponse{Status: true, Message: "Please check your mail for password reset code"}, w)91}92////// POST SECTION //////93// Signup handles signup request94func (ah *AuthenticationHandler) Signup(w http.ResponseWriter, r *http.Request) {95 w.Header().Set("Content-Type", "application/json")96 user := r.Context().Value(UserKey{}).(data.User)97 // hashedPass, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)98 // if err != nil {99 // ah.logger.Error("unable to hash password", "error", err)100 // w.WriteHeader(http.StatusInternalServerError)101 // // data.ToJSON(&GenericError{Error: err.Error()}, w)102 // data.ToJSON(&GenericResponse{Status: false, Message: UserCreationFailed}, w)103 // return104 // }105 hashedPass, err := ah.hashPassword(user.Password)106 if err != nil {107 w.WriteHeader(http.StatusInternalServerError)108 utils.ToJSON(&response.GenericResponse{Status: false, Message: UserCreationFailed}, w)109 return110 }111 user.Password = hashedPass112 user.TokenHash = utils.GenerateRandomString(15)113 err = ah.repo.Create(context.Background(), &user)114 if err != nil {115 ah.logger.Error("unable to insert user to database", "error", err)116 errMsg := err.Error()117 if strings.Contains(errMsg, PgDuplicateKeyMsg) {118 w.WriteHeader(http.StatusBadRequest)119 // data.ToJSON(&GenericError{Error: ErrUserAlreadyExists}, w)120 utils.ToJSON(&response.GenericResponse{Status: false, Message: ErrUserAlreadyExists}, w)121 } else {122 w.WriteHeader(http.StatusInternalServerError)123 // data.ToJSON(&GenericError{Error: errMsg}, w)124 utils.ToJSON(&response.GenericResponse{Status: false, Message: UserCreationFailed}, w)125 }126 return127 }128 // Send verification mail129 from := "ibrodex@gmail.com"130 to := []string{user.Email}131 subject := "Email Verification for Audio Book"132 mailType := service.MailConfirmation133 mailData := &service.MailData{134 Username: user.Username,135 Code: utils.GenerateRandomString(8),136 }137 mailReq := ah.mailService.NewMail(from, to, subject, mailType, mailData)138 err = ah.mailService.SendMail(mailReq)139 if err != nil {140 ah.logger.Error("unable to send mail", "error", err)141 w.WriteHeader(http.StatusInternalServerError)142 utils.ToJSON(&response.GenericResponse{Status: false, Message: UserCreationFailed}, w)143 return144 }145 verificationData := &data.VerificationData{146 Email: user.Email,147 Code: mailData.Code,148 Type: data.MailConfirmation,149 ExpiresAt: time.Now().Add(time.Hour * time.Duration(ah.configs.MailVerifCodeExpiration)),150 }151 err = ah.repo.StoreVerificationData(context.Background(), verificationData)152 if err != nil {153 ah.logger.Error("unable to store mail verification data", "error", err)154 w.WriteHeader(http.StatusInternalServerError)155 utils.ToJSON(&response.GenericResponse{Status: false, Message: UserCreationFailed}, w)156 return157 }158 ah.logger.Debug("User created successfully")159 w.WriteHeader(http.StatusCreated)160 // data.ToJSON(&GenericMessage{Message: "user created successfully"}, w)161 utils.ToJSON(&response.GenericResponse{Status: true, Message: "Please verify your email account using the confirmation code send to your mail"}, w)162}163func (ah *AuthenticationHandler) hashPassword(password string) (string, error) {164 hashedPass, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)165 if err != nil {166 ah.logger.Error("unable to hash password", "error", err)167 return "", err168 }169 return string(hashedPass), nil170}171// Login handles login request172func (ah *AuthenticationHandler) Login(w http.ResponseWriter, r *http.Request) {173 w.Header().Set("Content-Type", "application/json")174 reqUser := r.Context().Value(UserKey{}).(data.User)175 user, err := ah.repo.GetUserByEmail(context.Background(), reqUser.Email)176 if err != nil {177 ah.logger.Error("error fetching the user", "error", err)178 errMsg := err.Error()179 if strings.Contains(errMsg, PgNoRowsMsg) {180 w.WriteHeader(http.StatusBadRequest)181 // data.ToJSON(&GenericError{Error: ErrUserNotFound}, w)182 utils.ToJSON(&response.GenericResponse{Status: false, Message: ErrUserNotFound}, w)183 } else {184 w.WriteHeader(http.StatusInternalServerError)185 // data.ToJSON(&GenericError{Error: err.Error()}, w)186 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Unable to retrieve user from database.Please try again later"}, w)187 }188 return189 }190 if !user.IsVerified {191 ah.logger.Error("unverified user")192 w.WriteHeader(http.StatusUnauthorized)193 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Please verify your mail address before login"}, w)194 return195 }196 if valid := ah.authService.Authenticate(&reqUser, user); !valid {197 ah.logger.Debug("Authetication of user failed")198 w.WriteHeader(http.StatusBadRequest)199 // data.ToJSON(&GenericError{Error: "incorrect password"}, w)200 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Incorrect password"}, w)201 return202 }203 accessToken, err := ah.authService.GenerateAccessToken(user)204 if err != nil {205 ah.logger.Error("unable to generate access token", "error", err)206 w.WriteHeader(http.StatusInternalServerError)207 // data.ToJSON(&GenericError{Error: err.Error()}, w)208 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Unable to login the user. Please try again later"}, w)209 return210 }211 refreshToken, err := ah.authService.GenerateRefreshToken(user)212 if err != nil {213 ah.logger.Error("unable to generate refresh token", "error", err)214 w.WriteHeader(http.StatusInternalServerError)215 // data.ToJSON(&GenericError{Error: err.Error()}, w)216 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Unable to login the user. Please try again later"}, w)217 return218 }219 ah.logger.Debug("successfully generated token", "accesstoken", accessToken, "refreshtoken", refreshToken)220 w.WriteHeader(http.StatusOK)221 // data.ToJSON(&AuthResponse{AccessToken: accessToken, RefreshToken: refreshToken, Username: user.Username}, w)222 utils.ToJSON(&response.GenericResponse{223 Status: true,224 Message: "Successfully logged in",225 Data: &response.AuthResponse{AccessToken: accessToken, RefreshToken: refreshToken, Username: user.Username},226 }, w)227}228// VerifyMail verifies the provided confirmation code and set the User state to verified229func (ah *AuthenticationHandler) VerifyMail(w http.ResponseWriter, r *http.Request) {230 w.Header().Set("Content-Type", "application/json")231 ah.logger.Debug("verifying the confimation code")232 verificationData := r.Context().Value(VerificationDataKey{}).(data.VerificationData)233 verificationData.Type = data.MailConfirmation234 actualVerificationData, err := ah.repo.GetVerificationData(context.Background(), verificationData.Email, verificationData.Type)235 if err != nil {236 ah.logger.Error("unable to fetch verification data", "error", err)237 if strings.Contains(err.Error(), PgNoRowsMsg) {238 w.WriteHeader(http.StatusNotAcceptable)239 utils.ToJSON(&response.GenericResponse{Status: false, Message: ErrUserNotFound}, w)240 return241 }242 w.WriteHeader(http.StatusInternalServerError)243 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Unable to verify mail. Please try again later"}, w)244 return245 }246 valid, err := ah.verify(actualVerificationData, &verificationData)247 if !valid {248 w.WriteHeader(http.StatusNotAcceptable)249 utils.ToJSON(&response.GenericResponse{Status: false, Message: err.Error()}, w)250 return251 }252 // correct code, update user status to verified.253 err = ah.repo.UpdateUserVerificationStatus(context.Background(), verificationData.Email, true)254 if err != nil {255 ah.logger.Error("unable to set user verification status to true")256 w.WriteHeader(http.StatusInternalServerError)257 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Unable to verify mail. Please try again later"}, w)258 return259 }260 // delete the VerificationData from db261 err = ah.repo.DeleteVerificationData(context.Background(), verificationData.Email, verificationData.Type)262 if err != nil {263 ah.logger.Error("unable to delete the verification data", "error", err)264 }265 ah.logger.Debug("user mail verification succeeded")266 w.WriteHeader(http.StatusAccepted)267 utils.ToJSON(&response.GenericResponse{Status: true, Message: "Mail Verification succeeded"}, w)268}269// VerifyPasswordReset verifies the code provided for password reset270func (ah *AuthenticationHandler) VerifyPasswordReset(w http.ResponseWriter, r *http.Request) {271 w.Header().Set("Content-Type", "application/json")272 ah.logger.Debug("verifing password reset code")273 verificationData := r.Context().Value(VerificationDataKey{}).(data.VerificationData)274 verificationData.Type = data.PassReset275 actualVerificationData, err := ah.repo.GetVerificationData(context.Background(), verificationData.Email, verificationData.Type)276 if err != nil {277 ah.logger.Error("unable to fetch verification data", "error", err)278 if strings.Contains(err.Error(), PgNoRowsMsg) {279 w.WriteHeader(http.StatusNotAcceptable)280 utils.ToJSON(&response.GenericResponse{Status: false, Message: ErrUserNotFound}, w)281 return282 }283 w.WriteHeader(http.StatusInternalServerError)284 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Unable to reset password. Please try again later"}, w)285 return286 }287 valid, err := ah.verify(actualVerificationData, &verificationData)288 if !valid {289 w.WriteHeader(http.StatusNotAcceptable)290 utils.ToJSON(&response.GenericResponse{Status: false, Message: err.Error()}, w)291 return292 }293 respData := struct {294 Code string295 }{296 Code: verificationData.Code,297 }298 ah.logger.Debug("password reset code verification succeeded")299 w.WriteHeader(http.StatusAccepted)300 utils.ToJSON(&response.GenericResponse{Status: true, Message: "Password Reset code verification succeeded", Data: respData}, w)301}302func (ah *AuthenticationHandler) verify(actualVerificationData *data.VerificationData, verificationData *data.VerificationData) (bool, error) {303 // check for expiration304 if actualVerificationData.ExpiresAt.Before(time.Now()) {305 ah.logger.Error("verification data provided is expired")306 err := ah.repo.DeleteVerificationData(context.Background(), actualVerificationData.Email, actualVerificationData.Type)307 ah.logger.Error("unable to delete verification data from db", "error", err)308 return false, errors.New("Confirmation code has expired. Please try generating a new code")309 }310 if actualVerificationData.Code != verificationData.Code {311 ah.logger.Error("verification of mail failed. Invalid verification code provided")312 return false, errors.New("Verification code provided is Invalid. Please look in your mail for the code")313 }314 return true, nil315}316///////// PUT SECTION //////////////317// UpdateUsername handles username update request318func (ah *AuthenticationHandler) UpdateUsername(w http.ResponseWriter, r *http.Request) {319 w.Header().Set("Content-Type", "application/json")320 user := &data.User{}321 err := utils.FromJSON(user, r.Body)322 if err != nil {323 ah.logger.Error("unable to decode user json", "error", err.Error())324 w.WriteHeader(http.StatusBadRequest)325 // data.ToJSON(&GenericError{Error: err.Error()}, w)326 utils.ToJSON(&response.GenericResponse{Status: false, Message: err.Error()}, w)327 return328 }329 user.ID = r.Context().Value(UserIDKey{}).(string)330 ah.logger.Debug("udpating username for user : ", user)331 err = ah.repo.UpdateUsername(context.Background(), user)332 if err != nil {333 ah.logger.Error("unable to update username", "error", err)334 w.WriteHeader(http.StatusInternalServerError)335 // data.ToJSON(&GenericError{Error: err.Error()}, w)336 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Unable to update username. Please try again later"}, w)337 return338 }339 w.WriteHeader(http.StatusOK)340 // data.ToJSON(&UsernameUpdate{Username: user.Username}, w)341 utils.ToJSON(&response.GenericResponse{342 Status: true,343 Message: "Successfully updated username",344 Data: &request.UsernameUpdate{Username: user.Username},345 }, w)346}347// PasswordReset handles the password reset request348func (ah *AuthenticationHandler) ResetPassword(w http.ResponseWriter, r *http.Request) {349 w.Header().Set("Content-Type", "application/json")350 passResetReq := &request.PasswordResetReq{}351 err := utils.FromJSON(passResetReq, r.Body)352 if err != nil {353 ah.logger.Error("unable to decode password reset request json", "error", err.Error())354 w.WriteHeader(http.StatusBadRequest)355 utils.ToJSON(&response.GenericResponse{Status: false, Message: err.Error()}, w)356 return357 }358 userID := r.Context().Value(UserIDKey{}).(string)359 user, err := ah.repo.GetUserByID(context.Background(), userID)360 if err != nil {361 ah.logger.Error("unable to retrieve the user from db", "error", err)362 w.WriteHeader(http.StatusInternalServerError)363 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Unable to reset password. Please try again later"}, w)364 return365 }366 verificationData, err := ah.repo.GetVerificationData(context.Background(), user.Email, data.PassReset)367 if err != nil {368 ah.logger.Error("unable to retrieve the verification data from db", "error", err)369 w.WriteHeader(http.StatusInternalServerError)370 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Unable to reset password. Please try again later"}, w)371 return372 }373 if verificationData.Code != passResetReq.Code {374 // we should never be here.375 ah.logger.Error("verification code did not match even after verifying PassReset")376 w.WriteHeader(http.StatusInternalServerError)377 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Unable to reset password. Please try again later"}, w)378 return379 }380 if passResetReq.Password != passResetReq.PasswordRe {381 ah.logger.Error("password and password re-enter did not match")382 w.WriteHeader(http.StatusNotAcceptable)383 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Password and re-entered Password are not same"}, w)384 return385 }386 hashedPass, err := ah.hashPassword(passResetReq.Password)387 if err != nil {388 w.WriteHeader(http.StatusInternalServerError)389 utils.ToJSON(&response.GenericResponse{Status: false, Message: UserCreationFailed}, w)390 return391 }392 tokenHash := utils.GenerateRandomString(15)393 err = ah.repo.UpdatePassword(context.Background(), userID, hashedPass, tokenHash)394 if err != nil {395 ah.logger.Error("unable to update user password in db", "error", err)396 w.WriteHeader(http.StatusInternalServerError)397 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Password and re-entered Password are not same"}, w)398 return399 }400 // delete the VerificationData from db401 err = ah.repo.DeleteVerificationData(context.Background(), verificationData.Email, verificationData.Type)402 if err != nil {403 ah.logger.Error("unable to delete the verification data", "error", err)404 }405 w.WriteHeader(http.StatusOK)406 utils.ToJSON(&response.GenericResponse{Status: false, Message: "Password Reset Successfully"}, w)407}...

Full Screen

Full Screen

post.go

Source:post.go Github

copy

Full Screen

...17 // hashedPass, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)18 // if err != nil {19 // ah.logger.Error("unable to hash password", "error", err)20 // w.WriteHeader(http.StatusInternalServerError)21 // // data.ToJSON(&GenericError{Error: err.Error()}, w)22 // data.ToJSON(&GenericResponse{Status: false, Message: UserCreationFailed}, w)23 // return24 // }25 hashedPass, err := ah.hashPassword(user.Password)26 if err != nil {27 w.WriteHeader(http.StatusInternalServerError)28 data.ToJSON(&GenericResponse{Status: false, Message: UserCreationFailed}, w)29 return30 }31 user.Password = hashedPass32 user.TokenHash = utils.GenerateRandomString(15)33 err = ah.repo.Create(context.Background(), &user)34 if err != nil {35 ah.logger.Error("unable to insert user to database", "error", err)36 errMsg := err.Error()37 if strings.Contains(errMsg, PgDuplicateKeyMsg) {38 w.WriteHeader(http.StatusBadRequest)39 // data.ToJSON(&GenericError{Error: ErrUserAlreadyExists}, w)40 data.ToJSON(&GenericResponse{Status: false, Message: ErrUserAlreadyExists}, w)41 } else {42 w.WriteHeader(http.StatusInternalServerError)43 // data.ToJSON(&GenericError{Error: errMsg}, w)44 data.ToJSON(&GenericResponse{Status: false, Message: UserCreationFailed}, w)45 }46 return47 }48 // Send verification mail49 from := "vikisquarez@gmail.com"50 to := []string{user.Email}51 subject := "Email Verification for Bookite"52 mailType := service.MailConfirmation53 mailData := &service.MailData{54 Username: user.Username,55 Code: utils.GenerateRandomString(8),56 }57 mailReq := ah.mailService.NewMail(from, to, subject, mailType, mailData)58 err = ah.mailService.SendMail(mailReq)59 if err != nil {60 ah.logger.Error("unable to send mail", "error", err)61 w.WriteHeader(http.StatusInternalServerError)62 data.ToJSON(&GenericResponse{Status: false, Message: UserCreationFailed}, w)63 return64 }65 verificationData := &data.VerificationData{66 Email: user.Email,67 Code : mailData.Code,68 Type : data.MailConfirmation,69 ExpiresAt: time.Now().Add(time.Hour * time.Duration(ah.configs.MailVerifCodeExpiration)),70 }71 err = ah.repo.StoreVerificationData(context.Background(), verificationData)72 if err != nil {73 ah.logger.Error("unable to store mail verification data", "error", err)74 w.WriteHeader(http.StatusInternalServerError)75 data.ToJSON(&GenericResponse{Status: false, Message: UserCreationFailed}, w)76 return77 }78 ah.logger.Debug("User created successfully")79 w.WriteHeader(http.StatusCreated)80 // data.ToJSON(&GenericMessage{Message: "user created successfully"}, w)81 data.ToJSON(&GenericResponse{Status: true, Message: "Please verify your email account using the confirmation code send to your mail"}, w)82}83func (ah *AuthHandler) hashPassword(password string) (string, error) {84 hashedPass, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)85 if err != nil {86 ah.logger.Error("unable to hash password", "error", err)87 return "", err88 }89 return string(hashedPass), nil90}91// Login handles login request92func (ah *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {93 w.Header().Set("Content-Type", "application/json")94 reqUser := r.Context().Value(UserKey{}).(data.User)95 user, err := ah.repo.GetUserByEmail(context.Background(), reqUser.Email)96 if err != nil {97 ah.logger.Error("error fetching the user", "error", err)98 errMsg := err.Error()99 if strings.Contains(errMsg, PgNoRowsMsg) {100 w.WriteHeader(http.StatusBadRequest)101 // data.ToJSON(&GenericError{Error: ErrUserNotFound}, w)102 data.ToJSON(&GenericResponse{Status: false, Message: ErrUserNotFound}, w)103 } else {104 w.WriteHeader(http.StatusInternalServerError)105 // data.ToJSON(&GenericError{Error: err.Error()}, w)106 data.ToJSON(&GenericResponse{Status: false, Message: "Unable to retrieve user from database.Please try again later"}, w)107 }108 return109 }110 if !user.IsVerified {111 ah.logger.Error("unverified user")112 w.WriteHeader(http.StatusUnauthorized)113 data.ToJSON(&GenericResponse{Status: false, Message: "Please verify your mail address before login"}, w)114 return115 }116 if valid := ah.authService.Authenticate(&reqUser, user); !valid {117 ah.logger.Debug("Authetication of user failed")118 w.WriteHeader(http.StatusBadRequest)119 // data.ToJSON(&GenericError{Error: "incorrect password"}, w)120 data.ToJSON(&GenericResponse{Status: false, Message: "Incorrect password"}, w)121 return122 }123 accessToken, err := ah.authService.GenerateAccessToken(user)124 if err != nil {125 ah.logger.Error("unable to generate access token", "error", err)126 w.WriteHeader(http.StatusInternalServerError)127 // data.ToJSON(&GenericError{Error: err.Error()}, w)128 data.ToJSON(&GenericResponse{Status: false, Message: "Unable to login the user. Please try again later"}, w)129 return130 }131 refreshToken, err := ah.authService.GenerateRefreshToken(user)132 if err != nil {133 ah.logger.Error("unable to generate refresh token", "error", err)134 w.WriteHeader(http.StatusInternalServerError)135 // data.ToJSON(&GenericError{Error: err.Error()}, w)136 data.ToJSON(&GenericResponse{Status: false, Message: "Unable to login the user. Please try again later"}, w)137 return138 }139 ah.logger.Debug("successfully generated token", "accesstoken", accessToken, "refreshtoken", refreshToken)140 w.WriteHeader(http.StatusOK)141 // data.ToJSON(&AuthResponse{AccessToken: accessToken, RefreshToken: refreshToken, Username: user.Username}, w)142 data.ToJSON(&GenericResponse{143 Status: true,144 Message: "Successfully logged in",145 Data: &AuthResponse{AccessToken: accessToken, RefreshToken: refreshToken, Username: user.Username},146 }, w)147}148// VerifyMail verifies the provided confirmation code and set the User state to verified149func (ah *AuthHandler) VerifyMail(w http.ResponseWriter, r *http.Request) {150 w.Header().Set("Content-Type", "application/json")151 ah.logger.Debug("verifying the confimation code")152 verificationData := r.Context().Value(VerificationDataKey{}).(data.VerificationData)153 verificationData.Type = data.MailConfirmation154 actualVerificationData, err := ah.repo.GetVerificationData(context.Background(), verificationData.Email, verificationData.Type)155 if err != nil {156 ah.logger.Error("unable to fetch verification data", "error", err)157 if strings.Contains(err.Error(), PgNoRowsMsg) {158 w.WriteHeader(http.StatusNotAcceptable)159 data.ToJSON(&GenericResponse{Status: false, Message: ErrUserNotFound}, w)160 return161 }162 w.WriteHeader(http.StatusInternalServerError)163 data.ToJSON(&GenericResponse{Status: false, Message: "Unable to verify mail. Please try again later"}, w)164 return165 }166 valid, err := ah.verify(actualVerificationData, &verificationData)167 if !valid {168 w.WriteHeader(http.StatusNotAcceptable)169 data.ToJSON(&GenericResponse{Status: false, Message: err.Error()}, w)170 return171 }172 // correct code, update user status to verified.173 err = ah.repo.UpdateUserVerificationStatus(context.Background(), verificationData.Email, true)174 if err != nil {175 ah.logger.Error("unable to set user verification status to true")176 w.WriteHeader(http.StatusInternalServerError)177 data.ToJSON(&GenericResponse{Status: false, Message: "Unable to verify mail. Please try again later"}, w)178 return179 }180 // delete the VerificationData from db181 err = ah.repo.DeleteVerificationData(context.Background(), verificationData.Email, verificationData.Type)182 if err != nil {183 ah.logger.Error("unable to delete the verification data", "error", err)184 }185 ah.logger.Debug("user mail verification succeeded")186 w.WriteHeader(http.StatusAccepted)187 data.ToJSON(&GenericResponse{Status: true, Message: "Mail Verification succeeded"}, w)188}189// VerifyPasswordReset verifies the code provided for password reset190func (ah *AuthHandler) VerifyPasswordReset(w http.ResponseWriter, r *http.Request) {191 w.Header().Set("Content-Type", "application/json")192 ah.logger.Debug("verifing password reset code")193 verificationData := r.Context().Value(VerificationDataKey{}).(data.VerificationData)194 verificationData.Type = data.PassReset195 actualVerificationData, err := ah.repo.GetVerificationData(context.Background(), verificationData.Email, verificationData.Type)196 if err != nil {197 ah.logger.Error("unable to fetch verification data", "error", err)198 if strings.Contains(err.Error(), PgNoRowsMsg) {199 w.WriteHeader(http.StatusNotAcceptable)200 data.ToJSON(&GenericResponse{Status: false, Message: ErrUserNotFound}, w)201 return202 }203 w.WriteHeader(http.StatusInternalServerError)204 data.ToJSON(&GenericResponse{Status: false, Message: "Unable to reset password. Please try again later"}, w)205 return206 }207 valid, err := ah.verify(actualVerificationData, &verificationData)208 if !valid {209 w.WriteHeader(http.StatusNotAcceptable)210 data.ToJSON(&GenericResponse{Status: false, Message: err.Error()}, w)211 return212 }213 respData := struct{214 Code string215 }{216 Code: verificationData.Code,217 }218 ah.logger.Debug("password reset code verification succeeded")219 w.WriteHeader(http.StatusAccepted)220 data.ToJSON(&GenericResponse{Status: true, Message: "Password Reset code verification succeeded", Data: respData,}, w)221}222func (ah *AuthHandler) verify(actualVerificationData *data.VerificationData, verificationData *data.VerificationData) (bool, error) {223 // check for expiration224 if actualVerificationData.ExpiresAt.Before(time.Now()) {225 ah.logger.Error("verification data provided is expired")226 err := ah.repo.DeleteVerificationData(context.Background(), actualVerificationData.Email, actualVerificationData.Type)227 ah.logger.Error("unable to delete verification data from db", "error", err)228 return false, errors.New("Confirmation code has expired. Please try generating a new code")229 }230 if actualVerificationData.Code != verificationData.Code {231 ah.logger.Error("verification of mail failed. Invalid verification code provided")232 return false, errors.New("Verification code provided is Invalid. Please look in your mail for the code")233 }234 return true, nil...

Full Screen

Full Screen

ToJSON

Using AI Code Generation

copy

Full Screen

1import (2type Logger struct {3}4func (l *Logger) ToJSON(v interface{}) error {5 data, err := json.Marshal(v)6 if err != nil {7 }8 l.Printf("JSON: %s", data)9}10func main() {11 file, err := os.OpenFile("log.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)12 if err != nil {13 log.Fatalln("Failed to open log file", err)14 }15 defer file.Close()16 logger := log.New(file, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)17 l := &Logger{logger}18 l.Println("Starting the application...")19 l.Println("Something noteworthy happened")20 l.ToJSON(map[string]int{"foo": 42})21}22import (23type Logger struct {24}25func (l *Logger) ToJSON(v interface{}) error {26 data, err := json.Marshal(v)27 if err != nil {28 }29 l.Printf("JSON: %s", data)30}31func main() {32 file, err := os.OpenFile("log.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)33 if err != nil {34 log.Fatalln("Failed to open log file", err)35 }36 defer file.Close()37 logger := log.New(file, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)38 l := &Logger{logger}39 l.Println("Starting the application...")40 l.Println("Something noteworthy happened")41 l.ToJSON(map[string]int{"foo": 42})42}

Full Screen

Full Screen

ToJSON

Using AI Code Generation

copy

Full Screen

1log.ToJSON(log)2log.ToJSON(log)3log.ToJSON(log)4log.ToJSON(log)5log.ToJSON(log)6log.ToJSON(log)7log.ToJSON(log)8log.ToJSON(log)9log.ToJSON(log)10log.ToJSON(log)11log.ToJSON(log)12log.ToJSON(log)13log.ToJSON(log)14log.ToJSON(log)15log.ToJSON(log)16log.ToJSON(log)17log.ToJSON(log)18log.ToJSON(log)19log.ToJSON(log)20log.ToJSON(log)21log.ToJSON(log)22log.ToJSON(log)

Full Screen

Full Screen

ToJSON

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 beego.Info("this is info")4 beego.Warn("this is warn")5 beego.Debug("this is debug")6 beego.Error("this is error")7}8import (9func main() {10 var a interface{}11 beego.Info(a)12 beego.Warn(a)13 beego.Debug(a)14 beego.Error(a)15}16import (17func main() {18 var a interface{}19 beego.Info(a)20 beego.Warn(a)21 beego.Debug(a)22 beego.Error(a)23}24import (25func main() {26 var a interface{}27 beego.Info(a)28 beego.Warn(a)29 beego.Debug(a)30 beego.Error(a)31}32import (33func main() {34 var a interface{}35 a = []string{"a", "b", "c"}36 beego.Info(a)37 beego.Warn(a)38 beego.Debug(a)39 beego.Error(a)40}41import (42func main() {43 var a interface{}44 a = []int{1, 2, 3}45 beego.Info(a)46 beego.Warn(a)47 beego.Debug(a)48 beego.Error(a)49}50import (51func main() {52 var a interface{}53 a = []float64{1.2, 2.3, 3.4}54 beego.Info(a)55 beego.Warn(a)56 beego.Debug(a)57 beego.Error(a)58}

Full Screen

Full Screen

ToJSON

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 logger.ToJSON()4}5import (6func main() {7 logger.ToXML()8}9import (10func main() {11 logger.ToCSV()12}13import (14func main() {15 logger.ToYAML()16}17import (18func main() {19 logger.ToJSON()20}21import (22func main() {23 logger.ToYAML()24}25import (26func main() {27 logger.ToCSV()28}29import (30func main() {31 logger.ToXML()32}33import (34func main() {35 logger.ToJSON()36}37import (38func main() {39 logger.ToYAML()40}41import (42func main() {43 logger.ToXML()44}45import (

Full Screen

Full Screen

ToJSON

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 glog.Info("Starting the application...")4 glog.Info("Something noteworthy happened")5 glog.Warning("There is something you need to know about")6 glog.Error("Something went wrong!")7 time.Sleep(100 * time.Millisecond)8}9import (10func main() {11 glog.Info("Starting the application...")12 glog.Info("Something noteworthy happened")13 glog.Warning("There is something you need to know about")14 glog.Error("Something went wrong!")15 time.Sleep(100 * time.Millisecond)16}17import (18func main() {19 glog.Info("Starting the application...")20 glog.Info("Something noteworthy happened")21 glog.Warning("There is something you need to know about")22 glog.Error("Something went wrong!")23 time.Sleep(100 * time.Millisecond)24}25import (26func main() {27 glog.Info("Starting the application...")28 glog.Info("Something noteworthy happened")29 glog.Warning("There is something you need to know about")30 glog.Error("Something went wrong!")31 time.Sleep(100 * time.Millisecond)32}33import (34func main() {35 glog.Info("Starting the application...")36 glog.Info("Something noteworthy happened")37 glog.Warning("There is something you need to know about")38 glog.Error("Something went wrong!")39 time.Sleep(100 * time.Millisecond)40}41import (42func main() {43 glog.Info("Starting the application...")44 glog.Info("Something

Full Screen

Full Screen

ToJSON

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 log := impl.NewLogger()4 log.ToJSON()5}6import (7func main() {8 log := impl.NewLogger()9 log.ToXML()10}11import (12func main() {13 log := impl.NewLogger()14 log.ToYAML()15}16import (17func main() {18 log := impl.NewLogger()19 log.ToText()20}21import (22func main() {23 log := impl.NewLogger()24 log.ToCSV()25}26import (27func main() {28 log := impl.NewLogger()29 log.ToHTML()30}31import (32func main() {33 log := impl.NewLogger()34 log.ToJSON()35}36import (37func main() {

Full Screen

Full Screen

ToJSON

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 logger := log.New(os.Stdout, "INFO ", log.LstdFlags)4 logger.ToJSON(map[string]string{5 })6}7import (8func main() {9 logger := log.New(os.Stdout, "INFO ", log.LstdFlags)10 logger.ToJSON(map[string]string{11 })12}13import (14func main() {15 logger := log.New(os.Stdout, "INFO ", log.LstdFlags)16 logger.ToJSON(map[string]string{17 })18}19import (20func main() {21 logger := log.New(os.Stdout, "INFO ", log.LstdFlags)22 logger.ToJSON(map[string]string{23 })24}25import (26func main() {

Full Screen

Full Screen

ToJSON

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 log := logger.NewLogger()4 m := make(map[string]interface{})5 s := log.ToJSON(m)6 fmt.Println(s)7}8{"age":28,"name":"John"}9import (10func main() {11 log := logger.NewLogger()12 s := logger.Student{13 }14 s1 := log.ToJSON(s)15 fmt.Println(s1)16}17{"Age":28,"Grade":10,"Name":"John"}18import (19func main() {20 log := logger.NewLogger()21 s := []int{1, 2, 3, 4, 5}22 s1 := log.ToJSON(s)23 fmt.Println(s1)24}25import (26func main() {27 log := logger.NewLogger()28 s := []string{"John", "Doe", "Harry"}29 s1 := log.ToJSON(s)30 fmt.Println(s1)31}32import (33func main()

Full Screen

Full Screen

ToJSON

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 log := logger.NewLogger()4 log.ToJSON()5 fmt.Println("Done")6}7{"level":"info","message":"Done","timestamp":"2019-02-15T19:46:37+05:30"}8import (9func main() {10 log := logger.NewLogger()11 log.ToXML()12 fmt.Println("Done")13}14import (15func main() {16 log := logger.NewLogger()17 log.ToText()18 fmt.Println("Done")19}20import (21func main() {22 log := logger.NewLogger()23 log.ToCSV()24 fmt.Println("Done")25}

Full Screen

Full Screen

ToJSON

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 log = logger.Log{Level: "DEBUG", Message: "This is a test message"}4 fmt.Println(log.ToJSON())5}6import (7func main() {8 log = logger.Log{Level: "DEBUG", Message: "This is a test message"}9 fmt.Println(log.ToXML())10}11import (12func main() {13 log = logger.Log{Level: "DEBUG", Message: "This is a test message"}14 fmt.Println(log.ToCSV())15}16import (17func main() {18 log = logger.Log{Level: "DEBUG", Message: "This is a test message"}19 fmt.Println(log.ToText())20}21import (22func main() {23 log = logger.Log{Level: "DEBUG", Message: "This is a test message"}24 fmt.Println(log.ToHTML())25}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Gauge automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful