Initial commit

This commit is contained in:
Howl 2016-04-03 19:59:27 +02:00
commit 3ddab1de15
16 changed files with 583 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
api
api.conf

63
app/method.go Normal file
View File

@ -0,0 +1,63 @@
package app
import (
"database/sql"
"io/ioutil"
"github.com/gin-gonic/gin"
"github.com/osuripple/api/common"
)
// Method wraps an API method to a HandlerFunc.
func Method(f func(md common.MethodData) common.Response, db *sql.DB, privilegesNeeded ...int) gin.HandlerFunc {
return func(c *gin.Context) {
data, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
c.Error(err)
}
c.Request.Body.Close()
token := ""
switch {
case c.Request.Header.Get("X-Ripple-Token") != "":
token = c.Request.Header.Get("X-Ripple-Token")
case c.Query("token") != "":
token = c.Query("token")
case c.Query("k") != "":
token = c.Query("k")
}
md := common.MethodData{
DB: db,
RequestData: data,
C: c,
}
if token != "" {
tokenReal, exists := GetTokenFull(token, db)
if exists {
md.User = tokenReal
}
}
missingPrivileges := 0
for _, privilege := range privilegesNeeded {
if int(md.User.Privileges)&privilege == 0 {
missingPrivileges |= privilege
}
}
if missingPrivileges != 0 {
c.IndentedJSON(401, common.Response{
Code: 401,
Message: "You don't have the privilege(s): " + common.Privileges(missingPrivileges).String() + ".",
})
return
}
resp := f(md)
if resp.Code == 0 {
c.IndentedJSON(500, resp)
} else {
c.IndentedJSON(200, resp)
}
}
}

2
app/peppy/user.go Normal file
View File

@ -0,0 +1,2 @@
// Package peppy implements the osu! API as defined on the osu-api repository wiki (https://github.com/ppy/osu-api/wiki).
package peppy

33
app/start.go Normal file
View File

@ -0,0 +1,33 @@
package app
import (
"database/sql"
"github.com/gin-gonic/contrib/gzip"
"github.com/gin-gonic/gin"
"github.com/osuripple/api/app/v1"
"github.com/osuripple/api/common"
)
// Start begins taking HTTP connections.
func Start(conf common.Conf, db *sql.DB) {
r := gin.Default()
r.Use(gzip.Gzip(gzip.DefaultCompression))
api := r.Group("/api")
{
gv1 := api.Group("/v1")
{
gv1.GET("/user/:id", Method(v1.UserGET, db, common.PrivilegeRead))
gv1.GET("/ping", Method(v1.Ping, db))
gv1.GET("/surprise_me", Method(v1.SurpriseMe, db))
gv1.GET("/privileges", Method(v1.PrivilegesGET, db))
}
}
r.NoRoute(v1.Handle404)
if conf.Unix {
panic(r.RunUnix(conf.ListenTo))
}
panic(r.Run(conf.ListenTo))
}

26
app/tokens.go Normal file
View File

@ -0,0 +1,26 @@
package app
import (
"database/sql"
"github.com/osuripple/api/common"
)
// GetTokenFull retrieves an user ID and their token privileges knowing their API token.
func GetTokenFull(token string, db *sql.DB) (common.Token, bool) {
var uid int
var privs int
err := db.QueryRow("SELECT user, privileges FROM tokens WHERE token = ? LIMIT 1", token).Scan(&uid, &privs)
switch {
case err == sql.ErrNoRows:
return common.Token{}, false
case err != nil:
panic(err)
default:
return common.Token{
Value: token,
UserID: uid,
Privileges: common.Privileges(privs),
}, true
}
}

15
app/v1/404.go Normal file
View File

@ -0,0 +1,15 @@
package v1
import (
"github.com/gin-gonic/gin"
"github.com/osuripple/api/common"
)
// Handle404 handles requests with no implemented handlers.
func Handle404(c *gin.Context) {
c.IndentedJSON(404, common.Response{
Code: 404,
Message: "Oh dear... that API request could not be found! Perhaps the API is not up-to-date? Either way, have a surprise!",
Data: surpriseMe(),
})
}

13
app/v1/errors.go Normal file
View File

@ -0,0 +1,13 @@
package v1
import (
"github.com/osuripple/api/common"
)
// Boilerplate errors
var (
Err500 = common.Response{
Code: 0,
Message: "An error occurred. Try again, perhaps?",
}
)

116
app/v1/ping.go Normal file
View File

@ -0,0 +1,116 @@
package v1
import (
"math/rand"
"time"
"github.com/osuripple/api/common"
)
var rn = rand.New(rand.NewSource(time.Now().UnixNano()))
var kaomojis = [...]string{
"Σ(ノ°▽°)",
"( ƅ°ਉ°)ƅ",
"ヽ( ・∀・)ノ",
"˭̡̞(◞⁎˃ᆺ˂)◞*✰",
"(p^-^)p",
"(ノ^∇^)ノ゚",
"ヽ(〃・ω・)ノ",
"(۶* ‘ꆚ’)۶”",
"(。>ω<)。",
"(ノ。≧◇≦)ノ",
"ヾ(。・ω・)シ",
"(ノ・д・)ノ",
".+:。(ノ・ω・)ノ゙",
"Σ(*ノ´>ω<。`)ノ",
"ヾ(〃^∇^)ノ♪",
"\(@ ̄∇ ̄@)/",
"(^▽^)",
"ヾ(@^▽^@)",
"(((v)))",
"(*T▽T*)",
"\(^▽^)/",
"\(T∇T)/",
"ヽ( ★ω★)",
"ヽ(;▽;)",
"ヾ(。◕ฺ∀◕ฺ)",
"ヾ(@† ▽ †@)ノ",
"ヾ(^∇^)",
"ヾ(^▽^)ノ",
"ヾ(@^▽^@)ノ",
"ヾ(@゜▽゜@)ノ",
"(.=^・ェ・^=)",
"((≡^⚲͜^≡))",
"(^・o・^)ノ”",
"(^._.^)ノ",
"(^人^)",
"(=;ェ;=)",
"(=`ω´=)",
"(=`ェ´=)",
"=´∇`=",
"(=^・^=)",
"(=^・ェ・^=)",
"(=^‥^=)",
"(=TェT=)",
"(=xェx=)",
"(=^‥^)/`",
"~(=^‥^)/",
"└(=^‥^=)┐",
"ヾ(=゚・゚=)ノ",
"ヽ(=^・ω・^=)丿",
"d(=^・ω・^=)b",
"o(^・x・^)o",
"V(=^・ω・^=)v",
"(⁎˃ᆺ˂)",
"(,,^・⋏・^,,)",
}
var randomSentences = [...]string{
"Proudly sponsored by Kirotuso!",
"The brace is on fire!",
"deverupa ga daisuki!",
"It works!!!!",
"Feelin' groovy!",
"sudo rm -rf /",
"Hi! I'm Flowey! Flowey the flower!",
"Ripple devs are actually cats",
"Support Howl's fund for buying a power supply for his SSD",
}
func surpriseMe() string {
return randomSentences[rn.Intn(len(randomSentences))] + " " + kaomojis[rn.Intn(len(kaomojis))]
}
type pingData struct {
ID int `json:"user_id"`
Privileges int `json:"privileges"`
}
// Ping is a message to check with the API that we are logged in, and know what are our privileges.
func Ping(md common.MethodData) (r common.Response) {
r.Code = 200
if md.User.UserID == 0 {
r.Message = "You have not given us a token, so we don't know who you are! But you can still login with /api/v1/login " + kaomojis[rn.Intn(len(kaomojis))]
} else {
r.Message = surpriseMe()
}
r.Data = pingData{
ID: md.User.UserID,
Privileges: int(md.User.Privileges),
}
return
}
// SurpriseMe generates cute cats.
//
// ... Yes.
func SurpriseMe(md common.MethodData) (r common.Response) {
r.Code = 200
cats := make([]string, 100)
for i := 0; i < 100; i++ {
cats[i] = surpriseMe()
}
r.Data = cats
return
}

39
app/v1/privileges.go Normal file
View File

@ -0,0 +1,39 @@
package v1
import (
"github.com/osuripple/api/common"
)
type privilegesData struct {
PrivilegeRead bool `json:"read"`
PrivilegeReadConfidential bool `json:"read_confidential"`
PrivilegeWrite bool `json:"write"`
PrivilegeManageBadges bool `json:"manage_badges"`
PrivilegeBetaKeys bool `json:"beta_keys"`
PrivilegeManageSettings bool `json:"manage_settings"`
PrivilegeViewUserAdvanced bool `json:"view_user_advanced"`
PrivilegeManageUser bool `json:"manage_user"`
PrivilegeManageRoles bool `json:"manage_roles"`
PrivilegeManageAPIKeys bool `json:"manage_api_keys"`
PrivilegeBlog bool `json:"blog"`
}
// PrivilegesGET returns an explaination for the privileges, telling the client what they can do with this token.
func PrivilegesGET(md common.MethodData) (r common.Response) {
// This code sucks.
r.Code = 200
r.Data = privilegesData{
PrivilegeRead: md.User.Privileges.HasPrivilegeRead(),
PrivilegeReadConfidential: md.User.Privileges.HasPrivilegeReadConfidential(),
PrivilegeWrite: md.User.Privileges.HasPrivilegeWrite(),
PrivilegeManageBadges: md.User.Privileges.HasPrivilegeManageBadges(),
PrivilegeBetaKeys: md.User.Privileges.HasPrivilegeBetaKeys(),
PrivilegeManageSettings: md.User.Privileges.HasPrivilegeManageSettings(),
PrivilegeViewUserAdvanced: md.User.Privileges.HasPrivilegeViewUserAdvanced(),
PrivilegeManageUser: md.User.Privileges.HasPrivilegeManageUser(),
PrivilegeManageRoles: md.User.Privileges.HasPrivilegeManageRoles(),
PrivilegeManageAPIKeys: md.User.Privileges.HasPrivilegeManageAPIKeys(),
PrivilegeBlog: md.User.Privileges.HasPrivilegeBlog(),
}
return
}

82
app/v1/user.go Normal file
View File

@ -0,0 +1,82 @@
// Package v1 implements the first version of the Ripple API.
package v1
import (
"database/sql"
"fmt"
"strconv"
"strings"
"time"
"github.com/osuripple/api/common"
)
type userData struct {
ID int `json:"id"`
Username string `json:"username"`
UsernameAKA string `json:"username_aka"`
RegisteredOn time.Time `json:"registered_on"`
Rank int `json:"rank"`
LatestActivity time.Time `json:"latest_activity"`
Country string `json:"country"`
Badges []int `json:"badges"`
}
// UserGET is the API handler for GET /user/:id
func UserGET(md common.MethodData) (r common.Response) {
var err error
var uid int
uidStr := md.C.Param("id")
if uidStr == "self" {
uid = md.User.UserID
} else {
uid, err = strconv.Atoi(uidStr)
if err != nil {
r.Code = 400
r.Message = fmt.Sprintf("%s ain't a number", uidStr)
return
}
}
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=?", uid).Scan(
&user.ID, &user.Username, &registeredOn, &user.Rank, &latestActivity, &user.UsernameAKA, &badges, &user.Country, &showcountry)
switch {
case err == sql.ErrNoRows:
r.Code = 404
r.Message = "No such user was found!"
return
case err != nil:
md.C.Error(err)
r = Err500
return
}
user.RegisteredOn = time.Unix(registeredOn, 0)
user.LatestActivity = time.Unix(latestActivity, 0)
badgesSl := strings.Split(badges, ",")
for _, badge := range badgesSl {
if badge != "" && badge != "0" {
// We are ignoring errors because who really gives a shit if something's gone wrong on our end in this
// particular thing, we can just silently ignore this.
nb, err := strconv.Atoi(badge)
if err == nil && nb != 0 {
user.Badges = append(user.Badges, nb)
}
}
}
if !showcountry {
user.Country = "XX"
}
r.Code = 200
r.Data = user
return
}

39
common/conf.go Normal file
View File

@ -0,0 +1,39 @@
package common
import (
"fmt"
"github.com/thehowl/conf"
)
// Conf is the configuration file data for the ripple API.
// Conf uses https://github.com/thehowl/conf
type Conf struct {
DatabaseType string `description:"At the moment, 'mysql' is the only supported database type."`
DSN string `description:"The Data Source Name for the database. More: https://github.com/go-sql-driver/mysql#dsn-data-source-name"`
ListenTo string `description:"The IP/Port combination from which to take connections, e.g. :8080"`
Unix bool `description:"Bool indicating whether ListenTo is a UNIX socket or an address."`
}
var cachedConf *Conf
// Load creates a new Conf, using the data in the file "api.conf".
func Load() (c Conf, halt bool) {
if cachedConf != nil {
c = *cachedConf
return
}
err := conf.Load(&c, "api.conf")
halt = err == conf.ErrNoFile
if halt {
conf.MustExport(Conf{
DatabaseType: "mysql",
DSN: "root@/ripple",
ListenTo: ":40001",
Unix: false,
}, "api.conf")
fmt.Println("Please compile the configuration file (api.conf).")
}
cachedConf = &c
return
}

15
common/method_data.go Normal file
View File

@ -0,0 +1,15 @@
package common
import (
"database/sql"
"github.com/gin-gonic/gin"
)
// MethodData is a struct containing the data passed over to an API method.
type MethodData struct {
User Token
DB *sql.DB
RequestData []byte
C *gin.Context
}

100
common/privileges.go Normal file
View File

@ -0,0 +1,100 @@
package common
import "strings"
// These are the various privileges a token can have.
const (
PrivilegeRead = 1 << iota // pretty much public data: leaderboard, scores, user profiles (without confidential stuff like email)
PrivilegeReadConfidential // (eventual) private messages, reports... of self
PrivilegeWrite // change user information, write into confidential stuff...
PrivilegeManageBadges // can change various users' badges.
PrivilegeBetaKeys // can add, remove, upgrade/downgrade, make public beta keys.
PrivilegeManageSettings // maintainance, set registrations, global alerts, bancho settings
PrivilegeViewUserAdvanced // can see user email, and perhaps warnings in the future, basically.
PrivilegeManageUser // can change user email, allowed status, userpage, rank, username...
PrivilegeManageRoles // translates as admin, as they can basically assign roles to anyone, even themselves
PrivilegeManageAPIKeys // admin permission to manage user permission, not only self permissions. Only ever do this if you completely trust the application, because this essentially means to put the entire ripple database in the hands of a (potentially evil?) application.
PrivilegeBlog // can do pretty much anything to the blog, and the documentation.
)
// Privileges is a bitwise enum of the privileges of an user's API key.
type Privileges int
// HasPrivilegeRead returns whether the Read privilege is included in the privileges.
func (p Privileges) HasPrivilegeRead() bool {
return p&PrivilegeRead != 0
}
// HasPrivilegeReadConfidential returns whether the ReadConfidential privilege is included in the privileges.
func (p Privileges) HasPrivilegeReadConfidential() bool {
return p&PrivilegeReadConfidential != 0
}
// HasPrivilegeWrite returns whether the Write privilege is included in the privileges.
func (p Privileges) HasPrivilegeWrite() bool {
return p&PrivilegeWrite != 0
}
// HasPrivilegeManageBadges returns whether the ManageBadges privilege is included in the privileges.
func (p Privileges) HasPrivilegeManageBadges() bool {
return p&PrivilegeManageBadges != 0
}
// HasPrivilegeBetaKeys returns whether the BetaKeys privilege is included in the privileges.
func (p Privileges) HasPrivilegeBetaKeys() bool {
return p&PrivilegeBetaKeys != 0
}
// HasPrivilegeManageSettings returns whether the ManageSettings privilege is included in the privileges.
func (p Privileges) HasPrivilegeManageSettings() bool {
return p&PrivilegeManageSettings != 0
}
// HasPrivilegeViewUserAdvanced returns whether the ViewUserAdvanced privilege is included in the privileges.
func (p Privileges) HasPrivilegeViewUserAdvanced() bool {
return p&PrivilegeViewUserAdvanced != 0
}
// HasPrivilegeManageUser returns whether the ManageUser privilege is included in the privileges.
func (p Privileges) HasPrivilegeManageUser() bool {
return p&PrivilegeManageUser != 0
}
// HasPrivilegeManageRoles returns whether the ManageRoles privilege is included in the privileges.
func (p Privileges) HasPrivilegeManageRoles() bool {
return p&PrivilegeManageRoles != 0
}
// HasPrivilegeManageAPIKeys returns whether the ManageAPIKeys privilege is included in the privileges.
func (p Privileges) HasPrivilegeManageAPIKeys() bool {
return p&PrivilegeManageAPIKeys != 0
}
// HasPrivilegeBlog returns whether the Blog privilege is included in the privileges.
func (p Privileges) HasPrivilegeBlog() bool {
return p&PrivilegeBlog != 0
}
var privilegeString = [...]string{
"Read",
"ReadConfidential",
"Write",
"ManageBadges",
"BetaKeys",
"ManageSettings",
"ViewUserAdvanced",
"ManageUser",
"ManageRoles",
"ManageAPIKeys",
"Blog",
}
func (p Privileges) String() string {
var pvs []string
for i, v := range privilegeString {
if int(p)&(1<<uint(i)) != 0 {
pvs = append(pvs, v)
}
}
return strings.Join(pvs, ", ")
}

7
common/response.go Normal file
View File

@ -0,0 +1,7 @@
package common
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}

8
common/token.go Normal file
View File

@ -0,0 +1,8 @@
package common
// Token Is an API token.
type Token struct {
Value string
UserID int
Privileges Privileges
}

23
main.go Normal file
View File

@ -0,0 +1,23 @@
package main
import (
"database/sql"
"log"
// Golint pls dont break balls
_ "github.com/go-sql-driver/mysql"
"github.com/osuripple/api/app"
"github.com/osuripple/api/common"
)
func main() {
conf, halt := common.Load()
if halt {
return
}
db, err := sql.Open(conf.DatabaseType, conf.DSN)
if err != nil {
log.Fatal(err)
}
app.Start(conf, db)
}