PageRenderTime 40ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/bitbucket/bitbucket_demo.go

http://github.com/bradrydzewski/go.auth
Go | 101 lines | 59 code | 31 blank | 11 comment | 2 complexity | 8e1f50f61edbfb614a2f52ebca97271e MD5 | raw file
  1. package main
  2. import (
  3. "fmt"
  4. "flag"
  5. "net/http"
  6. "github.com/bradrydzewski/go.auth"
  7. )
  8. var homepage = `
  9. <html>
  10. <head>
  11. <title>Login</title>
  12. </head>
  13. <body>
  14. <div>Welcome to the go.auth Bitbucket demo</div>
  15. <div><a href="/auth/bitbucket">Authenticate with your Bitbucket Id</a><div>
  16. </body>
  17. </html>
  18. `
  19. var privatepage = `
  20. <html>
  21. <head>
  22. <title>Login</title>
  23. </head>
  24. <body>
  25. <div>oauth url: <a href="%s" target="_blank">%s</a></div>
  26. <div><a href="/auth/logout">Logout</a><div>
  27. </body>
  28. </html>
  29. `
  30. // private webpage, authentication required
  31. func Private(w http.ResponseWriter, r *http.Request) {
  32. user := r.URL.User.Username()
  33. fmt.Fprintf(w, fmt.Sprintf(privatepage, user, user))
  34. }
  35. // public webpage, no authentication required
  36. func Public(w http.ResponseWriter, r *http.Request) {
  37. fmt.Fprintf(w, homepage)
  38. }
  39. // logout handler
  40. func Logout(w http.ResponseWriter, r *http.Request) {
  41. auth.DeleteUserCookie(w, r)
  42. http.Redirect(w, r, "/", http.StatusSeeOther)
  43. }
  44. func main() {
  45. // You should pass in your access key and secret key as args.
  46. // Or you can set your access key and secret key by replacing the default values below (2nd input param in flag.String)
  47. consumerKey := flag.String("consumer_key", "[your bitbucket consumer key]", "your oauth consumer key")
  48. secretKey := flag.String("secret_key", "[your bitbucket secret key]", "your oauth secret key")
  49. flag.Parse()
  50. //url that google should re-direct to
  51. redirect := "http://localhost:8080/auth/bitbucket"
  52. // set the auth parameters
  53. auth.Config.CookieSecret = []byte("7H9xiimk2QdTdYI7rDddfJeV")
  54. auth.Config.LoginSuccessRedirect = "/private"
  55. auth.Config.CookieSecure = false
  56. // login handler
  57. bitbucketHandler := auth.Bitbucket(*consumerKey, *secretKey, redirect)
  58. http.Handle("/auth/bitbucket", bitbucketHandler)
  59. // logout handler
  60. http.HandleFunc("/auth/logout", Logout)
  61. // public urls
  62. http.HandleFunc("/", Public)
  63. // private, secured urls
  64. http.HandleFunc("/private", auth.SecureFunc(Private))
  65. println("bitbucket demo starting on port 8080")
  66. err := http.ListenAndServe(":8080", nil)
  67. if err != nil {
  68. fmt.Println(err)
  69. }
  70. }