Protecting routes on hte FE and improving authentication
This commit is contained in:
		@ -3,8 +3,11 @@ package models
 | 
			
		||||
import (
 | 
			
		||||
	"context"
 | 
			
		||||
	"database/sql"
 | 
			
		||||
	"errors"
 | 
			
		||||
	"strings"
 | 
			
		||||
	"time"
 | 
			
		||||
 | 
			
		||||
	"golang.org/x/crypto/bcrypt"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
// DBModel is the type for database connection values
 | 
			
		||||
@ -254,3 +257,26 @@ func (m *DBModel) GetUserByEmail(email string) (User, error) {
 | 
			
		||||
 | 
			
		||||
	return u, nil
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (m *DBModel) Authenticate(email, password string) (int, error) {
 | 
			
		||||
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
 | 
			
		||||
	defer cancel()
 | 
			
		||||
 | 
			
		||||
	var id int
 | 
			
		||||
	var hashedPassword string
 | 
			
		||||
 | 
			
		||||
	row := m.DB.QueryRowContext(ctx, "SELECT id, password from users WHERE email = ?", email)
 | 
			
		||||
	err := row.Scan(&id, &hashedPassword)
 | 
			
		||||
	if err != nil {
 | 
			
		||||
		return 0, err
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	err = bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
 | 
			
		||||
	if err == bcrypt.ErrMismatchedHashAndPassword {
 | 
			
		||||
		return 0, errors.New("incorrect password")
 | 
			
		||||
	} else if err != nil {
 | 
			
		||||
		return 0, err
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	return id, nil
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
		Reference in New Issue
	
	Block a user