github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/web/examples/userauth.go (about) 1 // Copyright 2014 <chaishushan{AT}gmail.com>. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // +build ingore 6 7 package main 8 9 import ( 10 "database/sql" 11 "log" 12 "os" 13 "strings" 14 "text/template" 15 16 _ "github.com/chai2010/gopkg/database/sqlite3" 17 "github.com/chai2010/gopkg/web" 18 ) 19 20 const dbfile = "./user.db" 21 22 const page = ` 23 <html> 24 <meta charset="utf-8"/> 25 <body> 26 {{if .Value}} 27 Hi {{.Value.RealName}}. 28 <form method="post" action="/logout"> 29 <input type="submit" name="method" value="logout" /> 30 </form> 31 You will logout after 10 seconds. Then try to reload. 32 {{else}} 33 {{if .Msg}}<b>{{.Msg}}</b>{{end}} 34 <form method="post" action="/login"> 35 <label for="name">Name:</label><br /> 36 <input type="text" id="userid" name="userid" value="" /><br /> 37 <label for="password">Password:</label><br /> 38 <input type="password" id="password" name="password" value="" /><br /> 39 <input type="submit" name="method" value="login" /> 40 </form> 41 {{end}} 42 </body> 43 </html> 44 ` 45 46 var tmpl = template.Must(template.New("x").Parse(page)) 47 var logger = log.New(os.Stdout, "", log.Ldate|log.Ltime) 48 var manager = web.NewSessionManager(logger) 49 50 type User struct { 51 UserId string 52 Password string 53 RealName string 54 Age int64 55 } 56 57 func getSession(ctx *web.Context, manager *web.SessionManager) *web.Session { 58 id, _ := ctx.GetSecureCookie("SessionId") 59 session := manager.GetSessionById(id) 60 ctx.SetSecureCookie("SessionId", web.Id, int64(manager.GetTimeout())) 61 ctx.SetHeader("Pragma", "no-cache", true) 62 return session 63 } 64 65 func getParam(ctx *web.Context, name string) string { 66 value, found := ctx.Params[name] 67 if found { 68 return strings.Trim(value, " ") 69 } 70 return "" 71 } 72 73 func dbSetup() { 74 if _, e := os.Stat(dbfile); e != nil { 75 db, e := sql.Open("sqlite3", dbfile) 76 if e != nil { 77 logger.Print(e) 78 return 79 } 80 for _, s := range []string{ 81 "create table User (userid varchar(16), password varchar(20), realname varchar(20), age integer)", 82 "insert into User values('go', 'lang', 'golang', 3)", 83 "insert into User values('perl', 'monger', 'perlmonger', 20)", 84 "insert into User values('japan', 'hello', '日本', 10)", 85 } { 86 if _, e := db.Exec(s); e != nil { 87 logger.Print(e) 88 return 89 } 90 } 91 db.Close() 92 } 93 } 94 95 func main() { 96 //------------------------------------------------ 97 // initialize session manager 98 manager.OnStart(func(session *web.Session) { 99 logger.Printf("Start session(\"%s\")", web.Id) 100 }) 101 manager.OnEnd(func(session *web.Session) { 102 logger.Printf("End session(\"%s\")", web.Id) 103 }) 104 manager.SetTimeout(10) 105 106 //------------------------------------------------ 107 // initialize database 108 dbSetup() 109 110 //------------------------------------------------ 111 // go to web 112 web.Config.CookieSecret = "7C19QRmwf3mHZ9CPAaPQ0hsWeufKd" 113 s := "select userid, password, realname, age from User where userid = ? and password = ?" 114 115 web.Get("/", func(ctx *web.Context) { 116 session := getSession(ctx, manager) 117 tmpl.Execute(ctx, map[string]interface{}{ 118 "Value": web.Value, "Msg": "", 119 }) 120 }) 121 web.Post("/login", func(ctx *web.Context) { 122 session := getSession(ctx, manager) 123 userid := getParam(ctx, "userid") 124 password := getParam(ctx, "password") 125 if userid != "" && password != "" { 126 // find user 127 db, e := sql.Open("sqlite3", dbfile) 128 defer db.Close() 129 st, _ := db.Prepare(s) 130 r, e := st.Query(userid, password) 131 if e != nil { 132 logger.Print(e) 133 return 134 } 135 if !r.Next() { 136 // not found 137 tmpl.Execute(ctx, map[string]interface{}{ 138 "Value": nil, "Msg": "User not found", 139 }) 140 return 141 } 142 var userid, password, realname string 143 var age int64 144 e = r.Scan(&userid, &password, &realname, &age) 145 if e != nil { 146 logger.Print(e) 147 return 148 } 149 // store User object to sessino 150 session.Value = &User{userid, password, realname, age} 151 logger.Printf("User \"%s\" login", session.Value.(*User).UserId) 152 } 153 ctx.Redirect(302, "/") 154 }) 155 web.Post("/logout", func(ctx *web.Context) { 156 session := getSession(ctx, manager) 157 if session.Value != nil { 158 // abandon 159 logger.Printf("User \"%s\" logout", session.Value.(*User).UserId) 160 session.Abandon() 161 } 162 ctx.Redirect(302, "/") 163 }) 164 web.Run(":6061") 165 }