ActivityPub/entities/user/userDatabaseConnector.go

133 lines
2.2 KiB
Go
Raw Normal View History

2020-10-17 10:13:15 +00:00
package user
import (
"fmt"
"git.nutfactory.org/hoernschen/ActivityPub/utils/database"
)
func CreateUser(user *User) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO user
(id, password, actor)
VALUES
(?, ?, ?)`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(user.Id, user.Password, user.Actor)
if err != nil {
tx.Rollback()
return
}
tx.Commit()
return
}
func CreateSession(userId string, token string) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO session
(token, userId)
VALUES
(?, ?)`)
tx, err := database.DB.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(token, userId)
if err != nil {
tx.Rollback()
return
}
tx.Commit()
return
}
func ReadUser(id string) (foundUser *User, err error) {
queryStmt := fmt.Sprintf(`SELECT id, password, actor
FROM user
WHERE id = '%s'`, id)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundUser = &User{}
err = rows.Scan(&foundUser.Id, &foundUser.Password, &foundUser.Actor)
if err != nil {
return
}
foundUser.Sessions, err = ReadSessionsForUser(foundUser.Id)
}
return
}
func ReadUserFromToken(token string) (foundUser *User, err error) {
queryStmt := fmt.Sprintf(`SELECT u.id, u.password, u.actor
FROM user as u
join session as s on u.id = s.userId
WHERE s.token = '%s'`, token)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundUser = &User{}
err = rows.Scan(&foundUser.Id, &foundUser.Password, &foundUser.Actor)
if err != nil {
return
}
foundUser.Sessions, err = ReadSessionsForUser(foundUser.Id)
}
return
}
func ReadSessionsForUser(userId string) (sessions []string, err error) {
queryStmt := fmt.Sprintf(`SELECT token
FROM session
WHERE userId = '%s'`, userId)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var session string
err = rows.Scan(&session)
if err != nil {
return
}
sessions = append(sessions, session)
}
return
}