transmet/user/user.go

63 lines
1.4 KiB
Go

package user
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
type User struct {
Username string
db *sql.DB
}
func UsernameExists(db *sql.DB, username string) (bool, error) {
rows, err := db.Query("SELECT count(username) FROM users where username=$1", username)
if err != nil {
fmt.Println("User DB Error: ", err)
return false, err
}
var count int
rows.Next()
rows.Scan(&count)
return count > 0, nil
}
func NewUserFromAuth(db *sql.DB, username, password string) *User {
fmt.Println("NewUserFromAuth:", username, ":", password)
rows, err := db.Query("SELECT username FROM users WHERE username = $1 AND password = crypt($2 ,gen_salt('bf'));", username, password)
if err != nil {
fmt.Println("Username or auth fail: ", err)
return nil
}
user := User{db: db}
if rows.Next() {
err := rows.Scan(&user.Username)
if err != nil {
fmt.Println("scan err: ", err)
}
} else {
return nil
}
return &user
}
func NewUserFromUsername(db *sql.DB, username string) *User {
rows, err := db.Query("SELECT username FROM users WHERE username=$1", username)
if err != nil {
fmt.Println("User DB Error: ", err)
return nil
}
user := User{db: db}
if rows.Next() {
err = rows.Scan(&user.Username)
if err != nil {
fmt.Println("Scan err: ", err)
}
} else {
fmt.Println("User DB Error: No user found with username ", username)
return nil
}
return &user
}