Advertisement
Guest User

Untitled

a guest
Nov 3rd, 2018
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. func comparePasswords(hashedPwd string, plainPwd []byte) bool {
  2. // Since we'll be getting the hashed password from the DB it
  3. // will be a string so we'll need to convert it to a byte slice
  4. byteHash := []byte(hashedPwd)
  5. err := bcrypt.CompareHashAndPassword(byteHash, plainPwd)
  6. if err != nil {
  7. log.Println(err)
  8. return false
  9. }
  10.  
  11. return true
  12. }
  13.  
  14. func hashAndSalt(pwd []byte) string {
  15.  
  16. // Use GenerateFromPassword to hash & salt pwd
  17. // MinCost is just an integer constant provided by the bcrypt
  18. // package along with DefaultCost & MaxCost.
  19. // The cost can be any value you want provided it isn't lower
  20. // than the MinCost (4)
  21. hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
  22. if err != nil {
  23. log.Println(err)
  24. }
  25. // GenerateFromPassword returns a byte slice so we need to
  26. // convert the bytes to a string and return it
  27. return string(hash)
  28. }
  29.  
  30. type SignUp struct {
  31. Username string `json:"username" binding:"required"`
  32. Password string `json:"password"`
  33. }
  34.  
  35. func Register(c *gin.Context) {
  36. signUp := SignUp{}
  37. if c.Bind(&signUp) != nil {
  38. c.JSON(http.StatusBadRequest, gin.H{"status": http.StatusBadRequest})
  39. return
  40. }
  41.  
  42. if len(signUp.Username) < 6 || len(signUp.Password) < 8 {
  43. c.JSON(http.StatusBadRequest, gin.H{"status": http.StatusBadRequest})
  44. return
  45. }
  46.  
  47. stmt, err := db.Prepare("INSERT User SET username=?,password=?")
  48. if err != nil {
  49. log.Panic(err)
  50. }
  51. res, err := stmt.Exec(signUp.Username, hashAndSalt([]byte(signUp.Password)))
  52. if err != nil {
  53. mysqlerr, ok := err.(*mysql.MySQLError)
  54. if ok && mysqlerr.Number == 1062 {
  55. c.JSON(http.StatusConflict, gin.H{"status": http.StatusConflict})
  56. }
  57. return
  58. }
  59. rows, err := res.RowsAffected()
  60. if err != nil {
  61. c.JSON(http.StatusBadRequest, gin.H{"status": http.StatusBadRequest})
  62. return
  63. }
  64. if rows != 1 {
  65. c.JSON(http.StatusBadRequest, gin.H{"status": http.StatusBadRequest})
  66. return
  67. }
  68.  
  69. c.JSON(http.StatusCreated, gin.H{"status": http.StatusCreated})
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement