Ejemplo n.º 1
0
func main() {
	s := "Password"
	p, err := bcrypt.GenerateFromPassword([]byte(s), bcrypt.DefaultCost)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(bcrypt.CompareHashAndPassword(p, []byte("Password")))
	fmt.Println(bcrypt.CompareHashAndPassword(p, []byte("Passwordadfadf")))
	fmt.Println(bcrypt.ErrMismatchedHashAndPassword)
}
Ejemplo n.º 2
0
func BasicAuth(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("WWW-Authenicate", `Basic realm="Restricted`)
		s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
		if len(s) != 2 {
			log.Warn(r.RemoteAddr, "auth Error")
			http.Error(w, "Not authorized", 401)
			return
		}

		b, err := base64.StdEncoding.DecodeString(s[1])
		if err != nil {
			http.Error(w, err.Error(), 401)
			return
		}
		pair := strings.SplitN(string(b), ":", 2)
		if len(pair) != 2 {
			log.Warn(r.RemoteAddr, " auth param empty")
			http.Error(w, "Not authorized", 401)
			return
		}

		params := mux.Vars(r)
		var account string
		var password string

		//super admin 可通過任何api
		if pair[0] == GlobalConf.AuthAccount && bcrypt.CompareHashAndPassword([]byte(GlobalConf.AuthPassword), []byte(pair[0]+pair[1])) == nil {
			h.ServeHTTP(w, r)
			return
		}

		if params["app_key"] != "" {
			data, err := Model.Get(params["app_key"])
			if err != nil {
				log.Warn(r.RemoteAddr, " ", err.Error())
				http.Error(w, err.Error(), 401)
				return
			}
			account = data.AuthAccount
			password = data.AuthPassword
		}

		if pair[0] != account || bcrypt.CompareHashAndPassword([]byte(password), []byte(pair[0]+pair[1])) != nil {
			log.Warn(r.RemoteAddr, " auth error "+pair[0]+" "+pair[1])
			http.Error(w, "Not authorized", 401)
			return
		}
		h.ServeHTTP(w, r)

	}
}
Ejemplo n.º 3
0
// Authenticate User
func authUser(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	buf := new(bytes.Buffer)
	auth := &struct {
		UserHandle string
		Password   string
	}{}
	buf.ReadFrom(r.Body)
	err := json.Unmarshal(buf.Bytes(), auth)
	if err != nil {
		writeJsonERR(w, 400, "Invalid JSON!")
		return
	}
	var passBuf []byte
	var id int
	err = db.QueryRow(`Select passwordbcrypt, id from users where email = $1 or handle = $1`, auth.UserHandle).Scan(&passBuf, &id)
	if err == sql.ErrNoRows {
		err = bcrypt.CompareHashAndPassword(passBuf, []byte(auth.Password))
		writeJsonERR(w, 400, "User name or password not found")
		return
	}
	if err != nil {
		fmt.Println(err)
		writeJsonERR(w, 500, "Server error!")
		return
	}
	err = bcrypt.CompareHashAndPassword(passBuf, []byte(auth.Password))
	if err != nil {
		writeJsonERR(w, 400, "User name or password not found")
		return
	}

	sessionKey, err1 := GetSessionKey(id)
	userAuth := &struct {
		Error     string
		UserID    int
		SessionID string
	}{"", id, sessionKey}

	if err1 != nil {
		panic(err1)
	}

	data, err := json.Marshal(userAuth)
	if err != nil {
		panic(err)
	}
	w.Write(data)
}
Ejemplo n.º 4
0
// NewBasic returns a negroni.HandlerFunc that authenticates via Basic auth using data store.
// Writes a http.StatusUnauthorized if authentication fails.
func NewBasic(datastore datastore.Datastore) negroni.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
		// Extract userid, password from request.
		userId, password := getCred(req)

		if userId == "" {
			requireAuth(w)
			return
		}

		// Extract hashed passwor from credentials.
		hashedPassword, found := datastore.Get(userId)
		if !found {
			requireAuth(w)
			return
		}

		// Check if the password is correct.
		err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
		// Password not correct. Fail.
		if err != nil {
			requireAuth(w)
			return
		}

		r := w.(negroni.ResponseWriter)

		// Password correct.
		if r.Status() != http.StatusUnauthorized {
			next(w, req)
		}
	}
}
Ejemplo n.º 5
0
// Login logs a user in. They will be redirected to dest or to the last
// location an authorization redirect was triggered (if found) on success. A
// message will be added to the session on failure with the reason.
func (a Authorizer) Login(rw http.ResponseWriter, req *http.Request, u string, p string, dest string) error {
	session, _ := a.cookiejar.Get(req, "auth")
	if session.Values["username"] != nil {
		return mkerror("already authenticated")
	}
	if user, err := a.backend.User(u); err == nil {
		verify := bcrypt.CompareHashAndPassword(user.Hash, []byte(p))
		if verify != nil {
			a.addMessage(rw, req, "Invalid username or password.")
			return mkerror("password doesn't match")
		}
	} else {
		a.addMessage(rw, req, "Invalid username or password.")
		return mkerror("user not found")
	}
	session.Values["username"] = u
	session.Save(req, rw)

	redirectSession, _ := a.cookiejar.Get(req, "redirects")
	if flashes := redirectSession.Flashes(); len(flashes) > 0 {
		dest = flashes[0].(string)
	}
	http.Redirect(rw, req, dest, http.StatusSeeOther)
	return nil
}
Ejemplo n.º 6
0
// CompareHash compares bcrypt password with a plaintext one. Returns true if passwords match
// and false if they do not.
func CompareHash(digest []byte, password string) bool {
	hex := []byte(password)
	if err := bcrypt.CompareHashAndPassword(digest, hex); err == nil {
		return true
	}
	return false
}
Ejemplo n.º 7
0
Archivo: main.go Proyecto: tynsh/kasse
// Authenticate tries to authenticate a given username/password combination
// against the database. It is guaranteed to take at least 200 Milliseconds. It
// returns ErrWrongAuth, if the user or password was wrong. If no error
// occured, it will return a fully populated User.
func (k *Kasse) Authenticate(username string, password []byte) (*User, error) {
	k.log.Printf("Verifying user %v", username)
	delay := time.After(200 * time.Millisecond)
	defer func() {
		<-delay
	}()

	user := new(User)
	if err := k.db.Get(user, `SELECT user_id, name, password FROM users WHERE name = $1`, username); err == sql.ErrNoRows {
		k.log.Printf("No such user %v", username)
		return nil, ErrWrongAuth
	} else if err != nil {
		return nil, err
	}

	if err := bcrypt.CompareHashAndPassword(user.Password, password); err == bcrypt.ErrMismatchedHashAndPassword {
		k.log.Println("Wrong password")
		return nil, ErrWrongAuth
	} else if err != nil {
		return nil, err
	}

	k.log.Printf("Successfully authenticated %v", username)
	return user, nil
}
Ejemplo n.º 8
0
func signinHandler(w http.ResponseWriter, r *http.Request) {
	var dbpassword []byte
	valid := false
	username := r.FormValue("suUsername")
	password := r.FormValue("suPassword")
	signinPassword := []byte(password)
	rows, err := db.Query("select username, password from users where username = $1;", username)
	util.CheckErr(err)
	log.Println(err)
	defer rows.Close()
	for rows.Next() {
		err := rows.Scan(&username, &dbpassword)
		util.CheckErr(err)
		log.Println(username)
		log.Println(dbpassword)
		log.Println(signinPassword)
		util.CheckErr(bcrypt.CompareHashAndPassword(dbpassword, signinPassword)) //if no message about nonmatch, successful login verification achieved
		//util.CheckErr(bcrypt.CompareHashAndPassword(dbpassword, hashedSigninPassword))
		if err == nil {
			valid = true
		}
	}
	err = rows.Err()
	util.CheckErr(err)
	fmt.Println(valid)
	if valid == true {
		http.Redirect(w, r, "http://localhost:8080/homepage/v.html", 302)
	}
}
Ejemplo n.º 9
0
func comparePasswordHash(passHash, plainpassword string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(passHash), []byte(plainpassword))
	if err != nil {
		return false
	}
	return true
}
Ejemplo n.º 10
0
//SignInPost handles POST /signin route, authenticates user
func SignInPost(c *gin.Context) {
	session := sessions.Default(c)
	user := &models.User{}
	if err := c.Bind(user); err != nil {
		session.AddFlash("Please, fill out form correctly.")
		session.Save()
		c.Redirect(http.StatusFound, "/signin")
		return
	}

	userDB, _ := models.GetUserByEmail(user.Email)
	if userDB.ID == 0 {
		logrus.Errorf("Login error, IP: %s, Email: %s", c.ClientIP(), user.Email)
		session.AddFlash("Email or password incorrect")
		session.Save()
		c.Redirect(http.StatusFound, "/signin")
		return
	}
	if err := bcrypt.CompareHashAndPassword([]byte(userDB.Password), []byte(user.Password)); err != nil {
		logrus.Errorf("Login error, IP: %s, Email: %s", c.ClientIP(), user.Email)
		session.AddFlash("Email or password incorrect")
		session.Save()
		c.Redirect(http.StatusFound, "/signin")
		return
	}

	session.Set("UserID", userDB.ID)
	session.Save()
	c.Redirect(http.StatusFound, "/")
}
Ejemplo n.º 11
0
func loginUser(w rest.ResponseWriter, r *rest.Request, db neutrino.DbService) {
	var u bson.M

	if err := r.DecodeJsonPayload(&u); err != nil {
		RestError(w, err)
		return
	}

	existingUser, err := db.FindId(u["email"].(string), nil)

	if err != nil {
		RestError(w, err)
		return
	}

	err = bcrypt.CompareHashAndPassword(existingUser["password"].([]byte), []byte(u["password"].(string)))

	if err != nil {
		RestError(w, err)
		return
	}

	token := jwt.New(jwt.GetSigningMethod("HS256"))
	token.Claims["user"] = u["email"].(string)
	token.Claims["expiration"] = time.Now().Add(time.Minute + 60).Unix()

	tokenStr, err := token.SignedString([]byte(""))

	if err != nil {
		RestError(w, err)
		return
	}

	w.WriteJson(map[string]string{"token": tokenStr})
}
Ejemplo n.º 12
0
func ValidatePassword(pwh, pw []byte) bool {
	err := bcrypt.CompareHashAndPassword(pwh, pw)
	if err != nil {
		return false
	}
	return true
}
Ejemplo n.º 13
0
func ValidLogin(email, password string) (bool, error) {
	const q = `SELECT * FROM user_ WHERE email = $1`

	var u user
	if err := db.QueryRow(q, email).Scan(
		&u.ID_,
		&u.Email,
		&u.Password,
		&u.Fullname,
		&u.Title,
		&u.Description,
		&u.AvatarURL,
		&u.VerificationCode,
		&u.IsAdmin_,
		&u.UpdatedAt,
		&u.CreatedAt,
	); err != nil {
		if err != sql.ErrNoRows {
			debug.Error(err)
			return false, err
		} else {
			err = nil
		}
	}

	if bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password)) != nil || u.VerificationCode != "verified" {
		return false, nil
	}

	return true, nil
}
Ejemplo n.º 14
0
func (ac *AuthController) Login(user models.User, r render.Render) {
	getuser := models.User{}
	session := ac.session.DB(os.Getenv("DB_NAME")).C("users")
	err := session.Find(bson.M{"email": user.Email}).One(&getuser)
	if err != nil {
		panic(err)
	}

	err = bcrypt.CompareHashAndPassword([]byte(getuser.Password), []byte(user.Password))

	if err != nil {
		panic(err)
	}

	token := jwt.New(jwt.GetSigningMethod("HS256"))
	token.Claims["user_id"] = getuser.Id
	token.Claims["email"] = getuser.Email
	token.Claims["exp"] = time.Now().Add(time.Minute * 5).Unix()
	tokenString, err := token.SignedString([]byte(SecretKey))
	if err != nil {
		r.JSON(500, map[string]interface{}{"_error": "500: Signing Error."})
		return
	}

	data := map[string]string{
		"token": tokenString,
	}

	r.JSON(200, data)
}
Ejemplo n.º 15
0
// ComparePassword will compare input password with hash password.
func ComparePassword(hash string, password string) bool {
	password = strings.Trim(password, " ")
	input := []byte(password)

	err := bcrypt.CompareHashAndPassword([]byte(hash), input)
	return (err == nil)
}
Ejemplo n.º 16
0
func (u *User) ValidatePassword(password string) bool {
	e := bcrypt.CompareHashAndPassword(u.HashedPassword, []byte(password))
	if e != nil {
		return false
	}
	return true
}
Ejemplo n.º 17
0
Archivo: user.go Proyecto: kylehq/gophr
func UpdateUser(user *User, email, currentPassword, newPassword string) (User, error) {
	out := *user
	out.Email = email

	// Check if the email exists
	existingUser, err := globalUserStore.FindByEmail(email)
	if err != nil {
		return out, err
	}
	if existingUser != nil && existingUser.ID != user.ID {
		return out, errEmailExists
	}
	// At this point, we can update the email address
	user.Email = email

	// No current password? Don't try update the password.
	if currentPassword == "" {
		return out, nil
	}
	if bcrypt.CompareHashAndPassword(
		[]byte(user.HashedPassword),
		[]byte(currentPassword),
	) != nil {
		return out, errPasswordIncorrect
	}
	if newPassword == "" {
		return out, errNoPassword
	}
	if len(newPassword) < passwordLength {
		return out, errPasswordTooShort
	}
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(newPassword), hashCost)
	user.HashedPassword = string(hashedPassword)
	return out, err
}
Ejemplo n.º 18
0
func authCompare(password, hash string) error {
	hashed, err := base64.StdEncoding.DecodeString(hash)
	if err != nil {
		return err
	}
	return bcrypt.CompareHashAndPassword(hashed, []byte(password))
}
Ejemplo n.º 19
0
func (c *Client) CreateUser(name, password string, admin bool) (*UserInfo, error) {
	c.mu.Lock()
	defer c.mu.Unlock()

	data := c.cacheData.Clone()

	// See if the user already exists.
	if u := data.User(name); u != nil {
		if err := bcrypt.CompareHashAndPassword([]byte(u.Hash), []byte(password)); err != nil || u.Admin != admin {
			return nil, ErrUserExists
		}
		return u, nil
	}

	// Hash the password before serializing it.
	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
	if err != nil {
		return nil, err
	}

	if err := data.CreateUser(name, string(hash), admin); err != nil {
		return nil, err
	}

	u := data.User(name)

	if err := c.commit(data); err != nil {
		return nil, err
	}

	return u, nil
}
Ejemplo n.º 20
0
func (BasicAuth) Authenticate(secret string) (types.Uid, time.Time, int) {
	uname, password, fail := parseSecret(secret)
	if fail != auth.NoErr {
		return types.ZeroUid, time.Time{}, fail
	}

	uid, passhash, expires, err := store.Users.GetAuthRecord("basic", uname)
	if err != nil {
		log.Println(err)
		return types.ZeroUid, time.Time{}, auth.ErrInternal
	} else if uid.IsZero() {
		// Invalid login.
		return types.ZeroUid, time.Time{}, auth.ErrFailed
	} else if !expires.IsZero() && expires.Before(time.Now()) {
		// The record has expired
		return types.ZeroUid, time.Time{}, auth.ErrExpired
	}

	err = bcrypt.CompareHashAndPassword([]byte(passhash), []byte(password))
	if err != nil {
		log.Println(err)
		// Invalid password
		return types.ZeroUid, time.Time{}, auth.ErrFailed
	}

	return uid, expires, auth.NoErr

}
Ejemplo n.º 21
0
func authClient(clientId, clientSecret string) error {
	acc, err := db.Search(clientId, "", 1, 0)
	if err != nil {
		return errors.InternalServerError("go.micro.srv.auth", "server_error")
	}

	if len(acc) == 0 {
		return errors.BadRequest("go.micro.srv.auth", "invalid_request")
	}

	// check the secret
	salt, secret, err := db.SaltAndSecret(acc[0].Id)
	if err != nil {
		return errors.InternalServerError("go.micro.srv.auth", "server_error")
	}

	s, err := base64.StdEncoding.DecodeString(secret)
	if err != nil {
		return errors.InternalServerError("go.micro.srv.auth", "server_error")
	}

	// does it match?
	if err := bcrypt.CompareHashAndPassword(s, []byte(x+salt+clientSecret)); err != nil {
		return errors.BadRequest("go.micro.srv.auth", "access_denied")
	}

	return nil
}
Ejemplo n.º 22
0
func ChangePassword(r *http.Request) error {
	u := ctx.Get(r, "user").(models.User)
	currentPw := r.FormValue("current_password")
	newPassword := r.FormValue("new_password")
	confirmPassword := r.FormValue("confirm_new_password")
	// Check the current password
	err := bcrypt.CompareHashAndPassword([]byte(u.Hash), []byte(currentPw))
	if err != nil {
		return ErrInvalidPassword
	}
	// Check that the new password isn't blank
	if newPassword == "" {
		return ErrEmptyPassword
	}
	// Check that new passwords match
	if newPassword != confirmPassword {
		return ErrPasswordMismatch
	}
	// Generate the new hash
	h, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	u.Hash = string(h)
	if err = models.PutUser(&u); err != nil {
		return err
	}
	return nil
}
Ejemplo n.º 23
0
// Process user login. TODO(gene): abstract out the authentication scheme
func (UsersObjMapper) Login(scheme, secret string) (types.Uid, error) {
	if scheme == "basic" {
		if splitAt := strings.Index(secret, ":"); splitAt > 0 {
			uname := secret[:splitAt]
			password := secret[splitAt+1:]

			uid, hash, err := adaptr.GetPasswordHash(uname)
			if err != nil {
				return types.ZeroUid, err
			} else if uid.IsZero() {
				// Invalid login
				return types.ZeroUid, nil
			}

			err = bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
			if err != nil {
				// Invalid password
				return types.ZeroUid, nil
			}
			//log.Println("Logged in as", uid, uid.String())
			return uid, nil
		} else {
			return types.ZeroUid, errors.New("store: invalid format of secret")
		}
	}
	return types.ZeroUid, errors.New("store: unknown authentication scheme '" + scheme + "'")
}
Ejemplo n.º 24
0
func BasicAuth() echo.HandlerFunc {
	return func(c *echo.Context) error {
		// Skip WebSocket
		if (c.Request().Header.Get(echo.Upgrade)) == echo.WebSocket {
			return nil
		}

		auth := c.Request().Header.Get(echo.Authorization)
		l := len(Basic)

		if len(auth) > l+1 && auth[:l] == Basic {
			b, err := base64.StdEncoding.DecodeString(auth[l+1:])
			if err == nil {
				cred := string(b)
				for i := 0; i < len(cred); i++ {
					if cred[i] == ':' {
						// Verify credentials
						for _, d := range conf.Domains {
							if cred[:i] == d.Name && bcrypt.CompareHashAndPassword([]byte(d.PassHash), []byte(cred[i+1:])) == nil {
								c.Set("domain", d)
								return nil
							}
						}
					}
				}
			}
		}
		c.Response().Header().Set(echo.WWWAuthenticate, Basic+" realm=Restricted")
		return echo.NewHTTPError(http.StatusUnauthorized)
	}
}
Ejemplo n.º 25
0
Archivo: client.go Proyecto: ryanj/dex
func (r *clientIdentityRepo) Authenticate(creds oidc.ClientCredentials) (bool, error) {
	m, err := r.executor(nil).Get(clientIdentityModel{}, creds.ID)
	if m == nil || err != nil {
		return false, err
	}

	cim, ok := m.(*clientIdentityModel)
	if !ok {
		log.Errorf("expected clientIdentityModel but found %v", reflect.TypeOf(m))
		return false, errors.New("unrecognized model")
	}

	dec, err := base64.URLEncoding.DecodeString(creds.Secret)
	if err != nil {
		log.Errorf("error Decoding client creds: %v", err)
		return false, nil
	}

	if len(dec) > maxSecretLength {
		return false, nil
	}

	ok = bcrypt.CompareHashAndPassword(cim.Secret, dec) == nil
	return ok, nil
}
Ejemplo n.º 26
0
func (u *BaseUser) ValidatePassword(password string) (bool, error) {
	if err := bcrypt.CompareHashAndPassword(u.passHash, []byte(password)); err != nil {
		return false, err
	}
	return true, nil

}
Ejemplo n.º 27
0
// VerifyPassword compare a field of an item payload containig a hashed password
// with a clear text password and return true if they match.
func VerifyPassword(hash interface{}, password []byte) bool {
	h, ok := hash.([]byte)
	if !ok {
		return false
	}
	return bcrypt.CompareHashAndPassword(h, password) == nil
}
Ejemplo n.º 28
0
func guess(hash []byte) {
	defer wg.Done()

	start := []byte("A")
	end := []byte("z")

	var x []byte = make([]byte, 10)

	for i := 0; i <= 2 && !found; i++ {
		for j := start[0]; j <= end[0] && !found; j++ {
			x[i] = j
			if bcrypt.CompareHashAndPassword(hash, x) == nil {
				found = true
			}
		}
	}

	if found {
		fmt.Println("found :)")
	} else {
		fmt.Println("not found")
	}

	return
}
Ejemplo n.º 29
0
func (mauth *MongoAuth) Authenticate(account string, password PasswordString) (bool, error) {
	// Copy our session
	tmp_session := mauth.session.Copy()
	// Close up when we are done
	defer tmp_session.Close()

	// Get Users from MongoDB
	glog.V(2).Infof("Checking user %s against Mongo Users. DB: %s, collection:%s",
		account, mauth.config.MongoConfig.DialInfo.Database, mauth.config.Collection)
	var dbUserRecord authUserEntry
	collection := tmp_session.DB(mauth.config.MongoConfig.DialInfo.Database).C(mauth.config.Collection)
	err := collection.Find(bson.M{"username": account}).One(&dbUserRecord)

	// If we connect and get no results we return a NoMatch so auth can fall-through
	if err == mgo.ErrNotFound {
		return false, NoMatch
	} else if err != nil {
		return false, err
	}

	// Validate db password against passed password
	if dbUserRecord.Password != nil {
		if bcrypt.CompareHashAndPassword([]byte(*dbUserRecord.Password), []byte(password)) != nil {
			return false, nil
		}
	}

	// Auth success
	return true, nil
}
Ejemplo n.º 30
-1
func tryCrypto() {
	pwd := "pwd"
	hash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
	if err != nil {
		P("bcrypt err: ", err)
	}

	P("first, pwd and hansh: \n", pwd, string(hash), len(string(hash)))
	hash2, _ := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
	P("second, pwd and hash: \n", pwd, string(hash2), len(string(hash2)))

	P("check pwd..")
	P("check hash1: ")
	err = bcrypt.CompareHashAndPassword(hash, []byte(pwd))
	P(err == nil)
	err = bcrypt.CompareHashAndPassword(hash, []byte("pwds"))
	P(err == nil)
	P("check has2:")
	P("hash1 != hash2: ", string(hash) != string(hash2))
	err = bcrypt.CompareHashAndPassword(hash2, []byte(pwd))
	P(err == nil)
	u := uuid.New()
	P("uuid: ", u, len(u), len(uuid.New()), len(uuid.New()))
	unix := time.Now().Unix()
	unixStr := fmt.Sprintf("%d", unix)
	P("time: ", unix, len(unixStr))

}