├── go-auth ├── run-go-auth.sh ├── Dockerfile ├── build.sh ├── docker-compose.yml ├── database │ ├── common.go │ ├── user.go │ └── token.go ├── logger │ └── log.go ├── user │ ├── user_test.go │ └── user.go ├── integration-test.sh ├── README.md ├── main.go ├── vendor │ └── vendor.json └── app │ └── app.go ├── README.md ├── .gitignore ├── deploy ├── docker-compose.yml └── rancher-compose.yml └── LICENSE /go-auth/run-go-auth.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ln -s /tmp/log /dev/log 4 | /bin/go-auth $@ -------------------------------------------------------------------------------- /go-auth/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu 2 | 3 | ADD ./go-auth /bin/go-auth 4 | 5 | EXPOSE 9000 6 | 7 | ADD run-go-auth.sh /bin/start-go-auth.sh 8 | 9 | ENTRYPOINT ["/bin/start-go-auth.sh"] -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-messenger 2 | 3 | A messenger application written in GO with two components. A RESTful user component for registering and tracking users and a real-time chat component. 4 | -------------------------------------------------------------------------------- /go-auth/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | docker run --rm -it \ 4 | -v $PWD:/go/src/go-messenger/go-auth/ \ 5 | -e SOURCE_PATH=go-messenger/go-auth/ \ 6 | usman/go-builder:1.8 7 | 8 | docker build -t usman/go-auth . 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | go-auth/go-auth 22 | *.exe 23 | *.test 24 | *.prof 25 | 26 | go-auth/vendor/* 27 | !vendor.json 28 | -------------------------------------------------------------------------------- /go-auth/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | 3 | services: 4 | Goauth: 5 | image: usman/go-auth:${GO_AUTH_VERSION:-latest} 6 | ports: 7 | - "9000:9000" 8 | command: 9 | - "-l" 10 | - "debug" 11 | - "run" 12 | - "--db-host" 13 | - "db" 14 | - "-p" 15 | - "9000" 16 | 17 | db: 18 | image: mysql 19 | environment: 20 | MYSQL_ROOT_PASSWORD: rootpass 21 | MYSQL_DATABASE: messenger 22 | MYSQL_USER: messenger 23 | MYSQL_PASSWORD: messenger 24 | 25 | -------------------------------------------------------------------------------- /deploy/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | services: 3 | Goauth: 4 | image: usman/go-auth:1.8 5 | command: 6 | - "-l" 7 | - "debug" 8 | - "run" 9 | - "--db-host" 10 | - "db" 11 | - "-p" 12 | - "9000" 13 | db: 14 | image: mysql 15 | environment: 16 | MYSQL_ROOT_PASSWORD: rootpass 17 | MYSQL_DATABASE: messenger 18 | MYSQL_USER: messenger 19 | MYSQL_PASSWORD: messenger 20 | 21 | auth-lb: 22 | image: rancher/lb-service-haproxy:v0.6.2 23 | ports: 24 | - 9000:9000/tcp 25 | labels: 26 | io.rancher.container.agent.role: environmentAdmin 27 | io.rancher.container.create_agent: 'true' -------------------------------------------------------------------------------- /deploy/rancher-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | services: 3 | Goauth: 4 | scale: 1 5 | start_on_create: true 6 | health_check: 7 | response_timeout: 2000 8 | healthy_threshold: 2 9 | port: 9000 10 | unhealthy_threshold: 3 11 | initializing_timeout: 60000 12 | interval: 2000 13 | strategy: recreate 14 | request_line: GET "/health" "HTTP/1.0" 15 | reinitializing_timeout: 6000 16 | auth-lb: 17 | scale: 1 18 | start_on_create: true 19 | lb_config: 20 | port_rules: 21 | - priority: 1 22 | protocol: http 23 | service: Goauth 24 | source_port: 9000 25 | target_port: 9000 26 | health_check: 27 | response_timeout: 2000 28 | healthy_threshold: 2 29 | port: 42 30 | unhealthy_threshold: 3 31 | interval: 2000 32 | db: 33 | scale: 1 34 | start_on_create: true -------------------------------------------------------------------------------- /go-auth/database/common.go: -------------------------------------------------------------------------------- 1 | package database 2 | 3 | import ( 4 | "database/sql" 5 | "fmt" 6 | 7 | _ "github.com/go-sql-driver/mysql" 8 | "github.com/op/go-logging" 9 | ) 10 | 11 | var log = logging.MustGetLogger("database") 12 | 13 | func Connect(provider string, user string, password string, dbHost string, 14 | dbPort int, dbname string) (UserData, TokenData, error) { 15 | 16 | db, _ := sql.Open(provider, fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", user, password, dbHost, dbPort, dbname)) 17 | err := db.Ping() 18 | if err != nil { 19 | return nil, nil, err 20 | } else { 21 | log.Debugf("Connected to DB %s:%d/%s", dbHost, dbPort, dbname) 22 | userData := UserDataS{db} 23 | tokenData := TokenDataS{db} 24 | 25 | err := userData.Init() 26 | if err != nil { 27 | return nil, nil, err 28 | } 29 | 30 | err = tokenData.Init() 31 | if err != nil { 32 | return nil, nil, err 33 | } 34 | return &userData, &tokenData, nil 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /go-auth/logger/log.go: -------------------------------------------------------------------------------- 1 | package logger 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/op/go-logging" 8 | ) 9 | 10 | var format = logging.MustStringFormatter( 11 | "%{color}%{time:15:04:05.000} %{shortfile} %{shortfunc} %{level:.10s} %{color:reset} %{message}", 12 | ) 13 | 14 | func SetupLogging(levelStr string, logType string) { 15 | level, err := logging.LogLevel(levelStr) 16 | if err != nil { 17 | fmt.Printf("Unable to understand log level %s\n", levelStr) 18 | return 19 | } 20 | var backend logging.Backend 21 | switch logType { 22 | case "syslog": 23 | backend, err = logging.NewSyslogBackend("go-auth") 24 | if err != nil { 25 | fmt.Printf("Unable to create syslog backend: %s\n", err.Error()) 26 | return 27 | } else { 28 | fmt.Printf("Logging to syslog\n") 29 | } 30 | case "console": 31 | backend = logging.NewLogBackend(os.Stderr, "", 0) 32 | default: 33 | fmt.Printf("Unrecognised log format") 34 | return 35 | } 36 | 37 | backendFormatter := logging.NewBackendFormatter(backend, format) 38 | backendLeveled := logging.AddModuleLevel(backendFormatter) 39 | 40 | backendLeveled.SetLevel(level, "") 41 | logging.SetBackend(backendLeveled) 42 | } 43 | -------------------------------------------------------------------------------- /go-auth/user/user_test.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "errors" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | type UserDataTest struct { 11 | } 12 | 13 | func TestRegisterOk(t *testing.T) { 14 | 15 | status := RegisterUser(&UserDataTest{}, "new", "password") 16 | assert.Equal(t, 200, status, "Expected 200 OK") 17 | } 18 | 19 | func TestRegisterInternalError(t *testing.T) { 20 | 21 | status := RegisterUser(&UserDataTest{}, "error-user", "password") 22 | assert.Equal(t, 500, status, "Expected 500 Internal Error") 23 | } 24 | 25 | func TestRegisterConflict(t *testing.T) { 26 | 27 | status := RegisterUser(&UserDataTest{}, "old", "password") 28 | assert.Equal(t, 409, status, "Expected 409 Conflict") 29 | } 30 | 31 | func (userData *UserDataTest) Init() error { 32 | return nil 33 | } 34 | 35 | func (userData *UserDataTest) DeleteUser(userId string) error { 36 | return nil 37 | } 38 | 39 | func (userData *UserDataTest) SaveUser(userId string, passwordHash []byte) error { 40 | if userId == "error-user" { 41 | return errors.New("Some Error") 42 | } else { 43 | return nil 44 | } 45 | } 46 | 47 | func (userData *UserDataTest) GetUser(userId string) ([]byte, error) { 48 | if userId == "new" { 49 | return nil, errors.New("Not Found") 50 | } else if userId == "old" { 51 | return []byte("someHash"), nil 52 | } else { 53 | return nil, nil 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /go-auth/integration-test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | function quit { 4 | docker-compose stop 5 | docker-compose rm -f 6 | exit $1 7 | } 8 | 9 | docker-compose up -d 10 | 11 | 12 | # Make sure containers are ready for the test 13 | sleep 20 14 | 15 | if [ "$(uname -s)" = "Darwin" ] ; then 16 | service_ip=$(docker-machine url $(docker-machine active) | cut -d : -f 2 | cut -c 3-) 17 | else 18 | service_container=$(docker ps -a | awk '{ print $1,$2 }' | grep go-auth | awk '{print $1 }') 19 | service_ip=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' ${service_container}) 20 | fi 21 | 22 | echo "Using Service IP $service_ip" 23 | 24 | 25 | first=$(curl -i -silent -X PUT -d userid=USERNAME -d password=PASSWORD ${service_ip}:9000/user | grep "HTTP/1.1") 26 | second=$(curl -i -silent -X PUT -d userid=USERNAME -d password=PASSWORD ${service_ip}:9000/user | grep "HTTP/1.1") 27 | 28 | status_first=$(echo "$first" | cut -f 2 -d ' ') 29 | status_second=$(echo "$second" | cut -f 2 -d ' ') 30 | 31 | if [[ "$status_first" -ne 200 ]]; then 32 | echo "Fail: Expecting 200 OK for first user register got $status_first" 33 | quit 1 34 | else 35 | echo "Pass: Register User" 36 | fi 37 | 38 | 39 | if [[ "$status_second" -ne 409 ]]; then 40 | echo "Fail: Expecting 409 OK for second user register got $status_second" 41 | quit 1 42 | else 43 | echo "Pass: Register User Conflict" 44 | fi 45 | 46 | quit 0 47 | 48 | 49 | -------------------------------------------------------------------------------- /go-auth/database/user.go: -------------------------------------------------------------------------------- 1 | package database 2 | 3 | import ( 4 | "database/sql" 5 | ) 6 | 7 | type UserData interface { 8 | Init() error 9 | SaveUser(string, []byte) error 10 | DeleteUser(string) error 11 | GetUser(string) ([]byte, error) 12 | } 13 | 14 | type UserDataS struct { 15 | db *sql.DB 16 | } 17 | 18 | func (userData *UserDataS) Init() error { 19 | // Create Table if Missing 20 | _, err := userData.db.Exec( 21 | `CREATE TABLE IF NOT EXISTS user ( 22 | userid VARCHAR(20) NOT NULL, 23 | password VARBINARY(60) NOT NULL, 24 | PRIMARY KEY (userid) 25 | )`) 26 | if err != nil { 27 | return err 28 | } else { 29 | log.Debugf("Created User Table") 30 | return nil 31 | } 32 | } 33 | 34 | func (userData *UserDataS) DeleteUser(userId string) error { 35 | _, err := userData.db.Exec(`DELETE from user where userid = ?`, userId) 36 | if err != nil { 37 | return err 38 | } else { 39 | return nil 40 | } 41 | } 42 | 43 | func (userData *UserDataS) SaveUser(userId string, passwordHash []byte) error { 44 | 45 | _, err := userData.db.Exec(`INSERT INTO user Values (?,?)`, userId, passwordHash) 46 | if err != nil { 47 | return err 48 | } else { 49 | return nil 50 | } 51 | } 52 | 53 | func (userData *UserDataS) GetUser(userId string) ([]byte, error) { 54 | 55 | var passwordHash []byte 56 | err := userData.db.QueryRow("select password from user where userid = ?", userId).Scan(&passwordHash) 57 | if err != nil { 58 | log.Infof("Error %s", err.Error()) 59 | return nil, err 60 | } else { 61 | log.Infof("User Exists %s", userId) 62 | return passwordHash, nil 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /go-auth/README.md: -------------------------------------------------------------------------------- 1 | # go-auth 2 | ## Dependencies 3 | 4 | * [Docker](http://docker.io) 5 | 6 | ## Usage 7 | 8 | go-auth - A RESTful Authentication Service with a Database backend 9 | 10 | USAGE: 11 | go-auth [global options] command [command options] [arguments...] 12 | 13 | VERSION: 14 | 0.0.0 15 | 16 | AUTHOR: 17 | Usman Ismail - 18 | 19 | COMMANDS: 20 | run Run the authentication service 21 | help, h Shows a list of commands or help for one command 22 | 23 | GLOBAL OPTIONS: 24 | --log-type -t "syslog, console" 25 | --log-level, -l "Info" The log level to use 26 | --help, -h show help 27 | --version, -v print the version 28 | 29 | # For Example 30 | go-auth -l debug run --db-host 192.168.59.103 -p 8080 31 | 32 | 33 | To run a containerized mysql database for your application use the following command: 34 | 35 | docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=rootpass \ 36 | -e MYSQL_DATABASE=messenger \ 37 | -e MYSQL_USER=messenger \ 38 | -e MYSQL_PASSWORD=messenger \ 39 | -p 3306:3306 mysql 40 | 41 | ##### To Add a new User 42 | 43 | curl -i -X PUT -d userid=USERNAME -d password=PASSWORD localhost:8080/user 44 | 45 | ##### To Delete a User 46 | 47 | curl -i -X DELETE 'localhost:8080/user?userid=USERNAME&password=PASSWORD' 48 | 49 | ##### To Get an Auth Token 50 | 51 | curl 'http://localhost:8080/token?userid=USERNAME&password=PASSWORD' 52 | 53 | ##### To Verify an Auth Token 54 | 55 | curl -i -X POST 'localhost:8080/token/USERNAME' --data "IHuzUHUuqCk5b5FVesX5LWBsqm8K...." 56 | 57 | ## Building 58 | 59 | ./build.sh 60 | -------------------------------------------------------------------------------- /go-auth/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/codegangsta/cli" 7 | "go-messenger/go-auth/app" 8 | "go-messenger/go-auth/logger" 9 | ) 10 | 11 | func main() { 12 | 13 | cliApp := cli.NewApp() 14 | cliApp.Name = "go-auth" 15 | cliApp.Author = "Usman Ismail" 16 | cliApp.Email = "usman@techtraits.com" 17 | cliApp.Usage = "A RESTful Authentication Service with a Database backend" 18 | cliApp.Commands = []cli.Command{getRunCommand()} 19 | cliApp.Flags = []cli.Flag{ 20 | cli.StringFlag{ 21 | Name: "log-level, l", 22 | Usage: "The log level to use", 23 | Value: "Info", 24 | }, 25 | cli.StringFlag{ 26 | Name: "log-type, t", 27 | Usage: "The log type to use. console or syslog", 28 | Value: "console", 29 | }, 30 | } 31 | cliApp.Run(os.Args) 32 | 33 | } 34 | 35 | func cliApplicationAction(c *cli.Context) { 36 | logger.SetupLogging(c.GlobalString("log-level"), c.GlobalString("log-type")) 37 | } 38 | func getRunCommand() cli.Command { 39 | 40 | actionRun := func(c *cli.Context) { 41 | cliApplicationAction(c) 42 | if !c.IsSet("db-host") { 43 | cli.ShowCommandHelp(c, "run") 44 | return 45 | } 46 | 47 | goAuthApp := app.NewApplication(c.String("db-user"), c.String("db-password"), 48 | c.String("database"), c.String("db-host"), c.Int("db-port"), c.Int("port")) 49 | 50 | goAuthApp.Run() 51 | 52 | } 53 | 54 | cmdRun := cli.Command{ 55 | Name: "run", 56 | Usage: "Run the authentication service", 57 | Action: actionRun, 58 | } 59 | 60 | cmdRun.Flags = []cli.Flag{ 61 | cli.StringFlag{ 62 | Name: "db-host", 63 | Usage: "The Database Hostname", 64 | }, 65 | cli.IntFlag{ 66 | Name: "db-port", 67 | Usage: "The Database port", 68 | Value: 3306, 69 | }, 70 | cli.StringFlag{ 71 | Name: "db-user", 72 | Usage: "The Database Username", 73 | Value: "messenger", 74 | }, 75 | cli.StringFlag{ 76 | Name: "db-password", 77 | Usage: "The Database Password", 78 | Value: "messenger", 79 | }, 80 | cli.StringFlag{ 81 | Name: "database", 82 | Usage: "The Database name", 83 | Value: "messenger", 84 | }, 85 | cli.IntFlag{ 86 | Name: "port, p", 87 | Usage: "The port on which this app will serve requests", 88 | Value: 8080, 89 | }, 90 | } 91 | 92 | return cmdRun 93 | } 94 | -------------------------------------------------------------------------------- /go-auth/database/token.go: -------------------------------------------------------------------------------- 1 | package database 2 | 3 | import ( 4 | "crypto/rand" 5 | "database/sql" 6 | "encoding/base64" 7 | "net/http" 8 | "time" 9 | ) 10 | 11 | type TokenData interface { 12 | Init() error 13 | CreateToken(string) (string, error) 14 | ValidateToken(string, string) (int, error) 15 | } 16 | 17 | type TokenDataS struct { 18 | db *sql.DB 19 | } 20 | 21 | func (tokenData *TokenDataS) Init() error { 22 | // Create Table if Missing 23 | _, err := tokenData.db.Exec( 24 | `CREATE TABLE IF NOT EXISTS token ( 25 | username VARCHAR(20) NOT NULL, 26 | token VARBINARY(256) NOT NULL, 27 | expiry TIMESTAMP NOT NULL, 28 | PRIMARY KEY (username) 29 | )`) 30 | if err != nil { 31 | return err 32 | } else { 33 | log.Debugf("Created Token Table") 34 | return nil 35 | } 36 | } 37 | 38 | func (tokenData *TokenDataS) CreateToken(userId string) (string, error) { 39 | 40 | token := make([]byte, 256) 41 | _, err := rand.Read(token) 42 | if err != nil { 43 | return "", err 44 | } 45 | 46 | timestamp := time.Now().Add(time.Hour).UTC().Format("2006-01-02 15:04:05") 47 | 48 | _, err = tokenData.db.Exec(`REPLACE INTO token Values (?,?,?)`, userId, token, timestamp) 49 | if err != nil { 50 | log.Debugf("Error %s", err.Error()) 51 | return "", err 52 | } else { 53 | return base64.StdEncoding.EncodeToString(token), nil 54 | } 55 | } 56 | 57 | func (tokenData *TokenDataS) ValidateToken(token string, username string) (int, error) { 58 | 59 | var usernameDB string 60 | var expiry string 61 | 62 | tokenBytes, err := base64.StdEncoding.DecodeString(token) 63 | if err != nil { 64 | log.Infof("Error %s", err.Error()) 65 | return http.StatusBadRequest, err 66 | } 67 | 68 | err = tokenData.db.QueryRow("select username,expiry from token where token.token = ?", tokenBytes).Scan(&usernameDB, &expiry) 69 | if err != nil { 70 | log.Infof("Error %s", err.Error()) 71 | return http.StatusBadRequest, err 72 | } 73 | 74 | if usernameDB != username { 75 | log.Infof("Token for wrong user") 76 | return http.StatusBadRequest, err 77 | } 78 | 79 | t, _ := time.Parse("2006-01-02 15:04:05", expiry) 80 | log.Debugf("Expiry %d Now %d", t.Unix(), time.Now().Unix()) 81 | if t.Before(time.Now()) { 82 | log.Debugf("Token Expired") 83 | return http.StatusBadRequest, err 84 | } 85 | return http.StatusOK, nil 86 | } 87 | -------------------------------------------------------------------------------- /go-auth/vendor/vendor.json: -------------------------------------------------------------------------------- 1 | { 2 | "comment": "", 3 | "ignore": "test", 4 | "package": [ 5 | { 6 | "checksumSHA1": "bplZOqTp6JAbkn25zHEPIob25WI=", 7 | "path": "github.com/codegangsta/cli", 8 | "revision": "2526b57c56f30b50466c96c4133b1a4ad0f0191f", 9 | "revisionTime": "2017-02-15T05:17:05Z" 10 | }, 11 | { 12 | "checksumSHA1": "OFu4xJEIjiI8Suu+j/gabfp+y6Q=", 13 | "origin": "github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew", 14 | "path": "github.com/davecgh/go-spew/spew", 15 | "revision": "4d4bfba8f1d1027c4fdbe371823030df51419987", 16 | "revisionTime": "2017-01-30T11:31:45Z" 17 | }, 18 | { 19 | "checksumSHA1": "QD6LqgLz2JMxXqns8TaxtK9AuHs=", 20 | "path": "github.com/go-sql-driver/mysql", 21 | "revision": "2e00b5cd70399450106cec6431c2e2ce3cae5034", 22 | "revisionTime": "2016-12-24T12:10:19Z" 23 | }, 24 | { 25 | "checksumSHA1": "F5dR3/i70EhSIMZfeIV+H8/PtvM=", 26 | "path": "github.com/gorilla/mux", 27 | "revision": "94e7d24fd285520f3d12ae998f7fdd6b5393d453", 28 | "revisionTime": "2017-02-17T19:26:16Z" 29 | }, 30 | { 31 | "checksumSHA1": "BoXdUBWB8UnSlFlbnuTQaPqfCGk=", 32 | "path": "github.com/op/go-logging", 33 | "revision": "970db520ece77730c7e4724c61121037378659d9", 34 | "revisionTime": "2016-03-15T20:05:05Z" 35 | }, 36 | { 37 | "checksumSHA1": "zKKp5SZ3d3ycKe4EKMNT0BqAWBw=", 38 | "origin": "github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/difflib", 39 | "path": "github.com/pmezard/go-difflib/difflib", 40 | "revision": "4d4bfba8f1d1027c4fdbe371823030df51419987", 41 | "revisionTime": "2017-01-30T11:31:45Z" 42 | }, 43 | { 44 | "checksumSHA1": "JXUVA1jky8ZX8w09p2t5KLs97Nc=", 45 | "path": "github.com/stretchr/testify/assert", 46 | "revision": "4d4bfba8f1d1027c4fdbe371823030df51419987", 47 | "revisionTime": "2017-01-30T11:31:45Z" 48 | }, 49 | { 50 | "checksumSHA1": "vE43s37+4CJ2CDU6TlOUOYE0K9c=", 51 | "path": "golang.org/x/crypto/bcrypt", 52 | "revision": "453249f01cfeb54c3d549ddb75ff152ca243f9d8", 53 | "revisionTime": "2017-02-08T20:51:15Z" 54 | }, 55 | { 56 | "checksumSHA1": "JsJdKXhz87gWenMwBeejTOeNE7k=", 57 | "path": "golang.org/x/crypto/blowfish", 58 | "revision": "453249f01cfeb54c3d549ddb75ff152ca243f9d8", 59 | "revisionTime": "2017-02-08T20:51:15Z" 60 | } 61 | ], 62 | "rootPath": "go-messenger/go-auth" 63 | } 64 | -------------------------------------------------------------------------------- /go-auth/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "github.com/op/go-logging" 5 | "go-messenger/go-auth/database" 6 | "golang.org/x/crypto/bcrypt" 7 | "net/http" 8 | ) 9 | 10 | var log = logging.MustGetLogger("user") 11 | 12 | type User interface { 13 | GetUserId() string 14 | GetPasswordHash() []byte 15 | } 16 | 17 | type UserS struct { 18 | userId string 19 | passwordHash []byte 20 | } 21 | 22 | func NewUser(userId string, password string) (User, error) { 23 | hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) 24 | if err != nil { 25 | return nil, err 26 | } else { 27 | return &UserS{userId, hash}, nil 28 | } 29 | } 30 | 31 | func GetUser(userId string, passwordHash []byte) User { 32 | return &UserS{userId, passwordHash} 33 | } 34 | 35 | func RegisterUser(userData database.UserData, userId string, password string) int { 36 | if len(userId) > 0 && len(password) > 0 { 37 | userObj, _ := NewUser(userId, password) 38 | // Check if user already exists 39 | user, err := userData.GetUser(userObj.GetUserId()) 40 | if user != nil { 41 | log.Warning("Duplicate username tried: %s", userId) 42 | return http.StatusConflict 43 | } 44 | // Save User to database 45 | err = userData.SaveUser(userObj.GetUserId(), userObj.GetPasswordHash()) 46 | if err != nil { 47 | log.Warning("Unable to create user: %s", err.Error()) 48 | return http.StatusInternalServerError 49 | } else { 50 | return http.StatusOK 51 | } 52 | } else { 53 | log.Debugf("Unable to create user, username or password missing") 54 | return http.StatusBadRequest 55 | } 56 | } 57 | 58 | func DeleteUser(userData database.UserData, userId string, password string) int { 59 | if len(userId) > 0 && len(password) > 0 { 60 | passwordHash, _ := userData.GetUser(userId) 61 | if passwordHash == nil { 62 | log.Warning("User not found, cannot delete: %s", userId) 63 | return http.StatusNotFound 64 | } else { 65 | if CompareHashAndPassword(passwordHash, password) == nil { 66 | userData.DeleteUser(userId) 67 | return http.StatusOK 68 | } else { 69 | return http.StatusBadRequest 70 | } 71 | 72 | } 73 | } else { 74 | log.Debugf("Unable to delete user, username or password missing") 75 | return http.StatusBadRequest 76 | } 77 | } 78 | 79 | func CompareHashAndPassword(hashedPassword []byte, password string) error { 80 | err := bcrypt.CompareHashAndPassword(hashedPassword, []byte(password)) 81 | if err != nil { 82 | log.Warning("Invalid password: %s", err.Error()) 83 | return err 84 | } else { 85 | return nil 86 | } 87 | } 88 | 89 | func (u *UserS) GetUserId() string { 90 | return u.userId 91 | } 92 | 93 | func (u *UserS) GetPasswordHash() []byte { 94 | return u.passwordHash 95 | } 96 | -------------------------------------------------------------------------------- /go-auth/app/app.go: -------------------------------------------------------------------------------- 1 | package app 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "io/ioutil" 7 | "net/http" 8 | "time" 9 | 10 | "github.com/gorilla/mux" 11 | "github.com/op/go-logging" 12 | "go-messenger/go-auth/database" 13 | "go-messenger/go-auth/user" 14 | ) 15 | 16 | type GoAuth interface { 17 | Run() 18 | } 19 | type GoAuthS struct { 20 | port int 21 | userData database.UserData 22 | tokenData database.TokenData 23 | } 24 | 25 | var log = logging.MustGetLogger("app") 26 | 27 | func NewApplication(dbUser string, dbPassword string, databaseName string, 28 | dbHost string, dbPort int, port int) GoAuth { 29 | 30 | err := errors.New("No connection") 31 | var userDB database.UserData 32 | var tokenDB database.TokenData 33 | for err != nil { 34 | log.Debugf("Connecting to database %s:%d\n", dbHost, dbPort) 35 | userDB, tokenDB, err = database.Connect("mysql", dbUser, dbPassword, dbHost, dbPort, databaseName) 36 | if err != nil { 37 | log.Debugf("Unable to connecto to database: %s. Retrying...\n", err.Error()) 38 | time.Sleep(5 * time.Second) 39 | } 40 | } 41 | 42 | log.Debugf("Connected to database") 43 | return &GoAuthS{port, userDB, tokenDB} 44 | } 45 | 46 | func (s *GoAuthS) Run() { 47 | r := mux.NewRouter() 48 | r.HandleFunc("/user", s.putUser).Methods("PUT") 49 | r.HandleFunc("/user", s.deleteUser).Methods("DELETE") 50 | r.HandleFunc("/token", s.getToken).Methods("GET") 51 | r.HandleFunc("/token/{username}", s.verifyToken).Methods("POST") 52 | r.HandleFunc("/health", s.getHealth).Methods("GET") 53 | http.Handle("/", r) 54 | log.Debugf("Listening on port %d", s.port) 55 | err := http.ListenAndServe(fmt.Sprintf(":%d", s.port), nil) 56 | if err != nil { 57 | log.Fatal("ListenAndServe: ", err) 58 | } 59 | } 60 | 61 | func (s *GoAuthS) putUser(w http.ResponseWriter, r *http.Request) { 62 | userId := r.FormValue("userid") 63 | password := r.FormValue("password") 64 | status := user.RegisterUser(s.userData, userId, password) 65 | if status != 200 { 66 | http.Error(w, "Unable to save user.", status) 67 | } 68 | } 69 | 70 | func (s *GoAuthS) deleteUser(w http.ResponseWriter, r *http.Request) { 71 | log.Infof("Delete User Called") 72 | userId := r.FormValue("userid") 73 | password := r.FormValue("password") 74 | status := user.DeleteUser(s.userData, userId, password) 75 | if status != 200 { 76 | http.Error(w, "Unable to delete user.", status) 77 | } 78 | } 79 | 80 | func (s *GoAuthS) getHealth(w http.ResponseWriter, r *http.Request) { 81 | log.Infof("Get Health Called") 82 | w.Write([]byte("ok")) 83 | } 84 | 85 | func (s *GoAuthS) getToken(w http.ResponseWriter, r *http.Request) { 86 | log.Infof("Get Token Called") 87 | userId := r.FormValue("userid") 88 | password := r.FormValue("password") 89 | 90 | passwordHash, err := s.userData.GetUser(userId) 91 | if err != nil { 92 | http.Error(w, "Unable to find user.", http.StatusNotFound) 93 | return 94 | } 95 | 96 | err = user.CompareHashAndPassword(passwordHash, password) 97 | if err != nil { 98 | http.Error(w, "Password not valid.", http.StatusBadRequest) 99 | return 100 | } 101 | 102 | token, err := s.tokenData.CreateToken(userId) 103 | if err != nil { 104 | http.Error(w, "Internal error.", http.StatusInternalServerError) 105 | return 106 | } 107 | 108 | w.Write([]byte(token)) 109 | } 110 | 111 | func (s *GoAuthS) verifyToken(w http.ResponseWriter, r *http.Request) { 112 | log.Infof("Verify Token Called") 113 | vars := mux.Vars(r) 114 | username := vars["username"] 115 | token, err := ioutil.ReadAll(r.Body) 116 | if err != nil { 117 | http.Error(w, "Unable to read token.", http.StatusBadRequest) 118 | return 119 | } 120 | 121 | status, _ := s.tokenData.ValidateToken(string(token[:]), username) 122 | if status != 200 { 123 | http.Error(w, "Unable to verify token.", status) 124 | } 125 | 126 | } 127 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | --------------------------------------------------------------------------------