Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func comparePasswords(hashedPwd string, plainPwd []byte) bool {
- // Since we'll be getting the hashed password from the DB it
- // will be a string so we'll need to convert it to a byte slice
- byteHash := []byte(hashedPwd)
- err := bcrypt.CompareHashAndPassword(byteHash, plainPwd)
- if err != nil {
- log.Println(err)
- return false
- }
- return true
- }
- func hashAndSalt(pwd []byte) string {
- // Use GenerateFromPassword to hash & salt pwd
- // MinCost is just an integer constant provided by the bcrypt
- // package along with DefaultCost & MaxCost.
- // The cost can be any value you want provided it isn't lower
- // than the MinCost (4)
- hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
- if err != nil {
- log.Println(err)
- }
- // GenerateFromPassword returns a byte slice so we need to
- // convert the bytes to a string and return it
- return string(hash)
- }
- type SignUp struct {
- Username string `json:"username" binding:"required"`
- Password string `json:"password"`
- }
- func Register(c *gin.Context) {
- signUp := SignUp{}
- if c.Bind(&signUp) != nil {
- c.JSON(http.StatusBadRequest, gin.H{"status": http.StatusBadRequest})
- return
- }
- if len(signUp.Username) < 6 || len(signUp.Password) < 8 {
- c.JSON(http.StatusBadRequest, gin.H{"status": http.StatusBadRequest})
- return
- }
- stmt, err := db.Prepare("INSERT User SET username=?,password=?")
- if err != nil {
- log.Panic(err)
- }
- res, err := stmt.Exec(signUp.Username, hashAndSalt([]byte(signUp.Password)))
- if err != nil {
- mysqlerr, ok := err.(*mysql.MySQLError)
- if ok && mysqlerr.Number == 1062 {
- c.JSON(http.StatusConflict, gin.H{"status": http.StatusConflict})
- }
- return
- }
- rows, err := res.RowsAffected()
- if err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"status": http.StatusBadRequest})
- return
- }
- if rows != 1 {
- c.JSON(http.StatusBadRequest, gin.H{"status": http.StatusBadRequest})
- return
- }
- c.JSON(http.StatusCreated, gin.H{"status": http.StatusCreated})
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement