User retrieval by both ID and username

This commit is contained in:
Howl 2016-04-03 23:09:28 +02:00
parent 2932ba3dd7
commit 6bae1e2390
2 changed files with 38 additions and 6 deletions

View File

@ -24,7 +24,8 @@ func Start(conf common.Conf, db *sql.DB) {
gv1.GET("/privileges", Method(v1.PrivilegesGET, db))
// Read privilege required
gv1.GET("/users/:id", Method(v1.UserGET, db, common.PrivilegeRead))
gv1.GET("/users/id/:id", Method(v1.UserByIDGET, db, common.PrivilegeRead))
gv1.GET("/users/name/:name", Method(v1.UserByNameGET, db, common.PrivilegeRead))
gv1.GET("/badges", Method(v1.BadgesGET, db, common.PrivilegeRead))
gv1.GET("/badges/:id", Method(v1.BadgeByIDGET, db, common.PrivilegeRead))
}

View File

@ -22,8 +22,8 @@ type userData struct {
Badges []int `json:"badges"`
}
// UserGET is the API handler for GET /user/:id
func UserGET(md common.MethodData) (r common.Response) {
// UserByIDGET is the API handler for GET /users/id/:id
func UserByIDGET(md common.MethodData) (r common.Response) {
var err error
var uid int
uidStr := md.C.Param("id")
@ -38,14 +38,45 @@ func UserGET(md common.MethodData) (r common.Response) {
}
}
user := userData{}
query := `
SELECT users.id, users.username, register_datetime, rank,
latest_activity, users_stats.username_aka, users_stats.badges_shown,
users_stats.country, users_stats.show_country
FROM users
LEFT JOIN users_stats
ON users.id=users_stats.id
WHERE users.id=?
LIMIT 1`
r = userPuts(md, md.DB.QueryRow(query, uid))
return
}
// UserByNameGET is the API handler for GET /users/name/:name
func UserByNameGET(md common.MethodData) (r common.Response) {
username := md.C.Param("name")
query := `
SELECT users.id, users.username, register_datetime, rank,
latest_activity, users_stats.username_aka, users_stats.badges_shown,
users_stats.country, users_stats.show_country
FROM users
LEFT JOIN users_stats
ON users.id=users_stats.id
WHERE users.username=?
LIMIT 1`
r = userPuts(md, md.DB.QueryRow(query, username))
return
}
func userPuts(md common.MethodData, row *sql.Row) (r common.Response) {
var err error
var user userData
registeredOn := int64(0)
latestActivity := int64(0)
var badges string
var showcountry bool
err = md.DB.QueryRow("SELECT users.id, users.username, register_datetime, rank, latest_activity, users_stats.username_aka, users_stats.badges_shown, users_stats.country, users_stats.show_country FROM users LEFT JOIN users_stats ON users.id=users_stats.id WHERE users.id=? LIMIT 1", uid).Scan(
&user.ID, &user.Username, &registeredOn, &user.Rank, &latestActivity, &user.UsernameAKA, &badges, &user.Country, &showcountry)
err = row.Scan(&user.ID, &user.Username, &registeredOn, &user.Rank, &latestActivity, &user.UsernameAKA, &badges, &user.Country, &showcountry)
switch {
case err == sql.ErrNoRows:
r.Code = 404