forked from RichardKnop/go-oauth2-server
/
main.go
104 lines (87 loc) · 2.31 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"log"
"os"
"github.com/RichardKnop/go-oauth2-server/accounts"
"github.com/RichardKnop/go-oauth2-server/config"
"github.com/RichardKnop/go-oauth2-server/database"
"github.com/RichardKnop/go-oauth2-server/migrations"
"github.com/RichardKnop/go-oauth2-server/oauth"
"github.com/RichardKnop/go-oauth2-server/routes"
"github.com/RichardKnop/go-oauth2-server/web"
"github.com/codegangsta/cli"
"github.com/codegangsta/negroni"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
)
var (
cliApp *cli.App
webApp *negroni.Negroni
)
func init() {
// Initialise a CLI app
cliApp = cli.NewApp()
cliApp.Name = "go-oauth2-server"
cliApp.Usage = "OAuth 2.0 Server"
cliApp.Author = "Richard Knop"
cliApp.Email = "risoknop@gmail.com"
cliApp.Version = "0.0.0"
}
func main() {
// Load the configuration, connect to the database
cnf := config.NewConfig()
db, err := database.NewDatabase(cnf)
if err != nil {
log.Fatal(err)
}
// Disable logging
db.LogMode(false)
// Set the CLI app commands
cliApp.Commands = []cli.Command{
{
Name: "migrate",
Usage: "run migrations",
Action: func(c *cli.Context) {
migrate(db)
},
},
{
Name: "runserver",
Usage: "run web server",
Action: func(c *cli.Context) {
runServer(cnf, db)
},
},
}
cliApp.Run(os.Args)
}
func migrate(db *gorm.DB) {
// Bootsrrap migrations
if err := migrations.Bootstrap(db); err != nil {
log.Fatal(err)
}
// Run migrations for the oauth service
if err := oauth.MigrateAll(db); err != nil {
log.Fatal(err)
}
}
func runServer(cnf *config.Config, db *gorm.DB) {
// Initialise the oauth service
oauthService := oauth.NewService(cnf, db)
// Initialise the accounts service
_ = accounts.NewService(cnf, db, oauthService)
// Initialise the web service
_ = web.NewService(cnf, oauthService)
// Start a classic negroni app
webApp := negroni.Classic()
// Create a router instance
router := mux.NewRouter().StrictSlash(true)
// Add routes for the oauth package (REST tokens endpoint)
routes.AddRoutes(oauth.Routes, router.PathPrefix("/api/v1/oauth").Subrouter())
// Add routes for the web package (register, login authorize web pages)
routes.AddRoutes(web.Routes, router.PathPrefix("/web").Subrouter())
// Set the router
webApp.UseHandler(router)
// Run the server on port 8080
webApp.Run(":8080")
}