2020-12-20 19:00:59 +01:00
|
|
|
package sql
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2024-10-26 14:56:17 +02:00
|
|
|
"github.com/semaphoreui/semaphore/db"
|
2020-12-20 19:00:59 +01:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2021-03-12 18:41:41 +01:00
|
|
|
func (d *SqlDb) CreateSession(session db.Session) (db.Session, error) {
|
|
|
|
err := d.sql.Insert(&session)
|
|
|
|
return session, err
|
|
|
|
}
|
|
|
|
|
2020-12-20 19:00:59 +01:00
|
|
|
func (d *SqlDb) CreateAPIToken(token db.APIToken) (db.APIToken, error) {
|
2024-07-22 08:14:06 +02:00
|
|
|
token.Created = db.GetParsedTime(time.Now().UTC())
|
2020-12-20 19:00:59 +01:00
|
|
|
err := d.sql.Insert(&token)
|
|
|
|
return token, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *SqlDb) GetAPIToken(tokenID string) (token db.APIToken, err error) {
|
2022-01-31 22:30:36 +01:00
|
|
|
err = d.selectOne(&token, d.PrepareQuery("select * from user__token where id=? and expired=false"), tokenID)
|
2020-12-20 19:00:59 +01:00
|
|
|
|
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
err = db.ErrNotFound
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-03-31 12:34:05 +02:00
|
|
|
func (d *SqlDb) ExpireAPIToken(userID int, tokenID string) error {
|
|
|
|
return validateMutationResult(d.exec("update user__token set expired=true where id=? and user_id=?", tokenID, userID))
|
2020-12-20 19:00:59 +01:00
|
|
|
}
|
|
|
|
|
2022-11-09 09:10:42 +01:00
|
|
|
func (d *SqlDb) DeleteAPIToken(userID int, tokenID string) (err error) {
|
|
|
|
_, err = d.sql.Delete(db.APIToken{
|
|
|
|
ID: tokenID,
|
|
|
|
UserID: userID,
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-12-20 19:00:59 +01:00
|
|
|
func (d *SqlDb) GetSession(userID int, sessionID int) (session db.Session, err error) {
|
2021-08-24 17:20:34 +02:00
|
|
|
err = d.selectOne(&session, "select * from session where id=? and user_id=? and expired=false", sessionID, userID)
|
2020-12-20 19:00:59 +01:00
|
|
|
|
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
err = db.ErrNotFound
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *SqlDb) ExpireSession(userID int, sessionID int) error {
|
2021-08-24 17:20:34 +02:00
|
|
|
res, err := d.exec("update session set expired=1 where id=? and user_id=?", sessionID, userID)
|
2020-12-20 19:00:59 +01:00
|
|
|
|
|
|
|
return validateMutationResult(res, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *SqlDb) TouchSession(userID int, sessionID int) error {
|
2024-07-22 08:14:06 +02:00
|
|
|
_, err := d.exec("update session set last_active=? where id=? and user_id=?", time.Now().UTC(), sessionID, userID)
|
2020-12-20 19:00:59 +01:00
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *SqlDb) GetAPITokens(userID int) (tokens []db.APIToken, err error) {
|
2022-01-31 22:30:36 +01:00
|
|
|
_, err = d.selectAll(&tokens, d.PrepareQuery("select * from user__token where user_id=?"), userID)
|
2020-12-20 19:00:59 +01:00
|
|
|
|
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
err = db.ErrNotFound
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|