transmet/user/user.go

67 lines
1.5 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
}
defer rows.Close()
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)
rows, err := db.Query("SELECT username FROM users WHERE username = $1 AND password IS NOT NULL AND password = crypt($2 , password);", username, password)
if err != nil {
fmt.Println("Username or auth fail: ", err)
return nil
}
defer rows.Close()
user := User{db: db}
if rows.Next() {
err := rows.Scan(&user.Username)
if err != nil {
fmt.Println("scan err: ", err)
}
} else {
fmt.Println("no match")
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
}
defer rows.Close()
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
}