transmet/user/user.go

67 lines
1.5 KiB
Go
Raw Normal View History

2015-04-30 04:32:39 +00:00
package user
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
type User struct {
2015-09-13 21:57:22 +00:00
Username string
db *sql.DB
2015-04-30 04:32:39 +00:00
}
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
}
2015-05-18 03:18:28 +00:00
defer rows.Close()
2015-04-30 04:32:39 +00:00
var count int
rows.Next()
rows.Scan(&count)
return count > 0, nil
}
func NewUserFromAuth(db *sql.DB, username, password string) *User {
2015-05-16 19:48:42 +00:00
fmt.Println("NewUserFromAuth:", username)
2015-05-02 19:28:11 +00:00
rows, err := db.Query("SELECT username FROM users WHERE username = $1 AND password IS NOT NULL AND password = crypt($2 , password);", username, password)
2015-04-30 04:32:39 +00:00
if err != nil {
2015-05-02 17:13:33 +00:00
fmt.Println("Username or auth fail: ", err)
2015-04-30 04:32:39 +00:00
return nil
}
2015-05-18 03:18:28 +00:00
defer rows.Close()
2015-04-30 04:32:39 +00:00
user := User{db: db}
if rows.Next() {
2015-05-02 17:13:33 +00:00
err := rows.Scan(&user.Username)
2015-04-30 04:32:39 +00:00
if err != nil {
fmt.Println("scan err: ", err)
}
} else {
2015-09-13 21:57:22 +00:00
fmt.Println("no match")
2015-04-30 04:32:39 +00:00
return nil
}
2015-05-02 17:13:33 +00:00
return &user
2015-04-30 04:32:39 +00:00
}
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
}
2015-05-18 03:18:28 +00:00
defer rows.Close()
2015-04-30 04:32:39 +00:00
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
}