Skip to content

Commit

Permalink
Session information retrieval
Browse files Browse the repository at this point in the history
  • Loading branch information
thehowl committed Mar 8, 2018
1 parent eb587b8 commit 34593de
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
12 changes: 10 additions & 2 deletions http/api/api.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
package api

import "zxq.co/ripple/misirlou-api/http"
import (
"strconv"

"zxq.co/ripple/misirlou-api/http"
)

func Home(c *http.Context) {
c.WriteString("Misirlou API 2.0\nhttps://zxq.co/ripple/misirlou-api")
c.WriteString("Misirlou API 2.0\nhttps://zxq.co/ripple/misirlou-api\n")
s := c.Session()
if s != nil {
c.WriteString("Ripple User: " + strconv.Itoa(s.UserID))
}
}

func init() {
Expand Down
34 changes: 31 additions & 3 deletions http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ package http

import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net"
Expand Down Expand Up @@ -92,8 +94,10 @@ func wrapper(o Options, f func(*Context)) fasthttp.RequestHandler {
type Context struct {
Options

ctx *fasthttp.RequestCtx
ip net.IP
sessCached bool
sess *models.Session
ctx *fasthttp.RequestCtx
ip net.IP
}

// Header retrieves a header from the request.
Expand All @@ -112,11 +116,15 @@ func (c *Context) SetCode(i int) {
c.ctx.SetStatusCode(i)
}

func (c *Context) reportError(err error) {
fmt.Fprintln(os.Stderr, err)
}

// Error closes the request with a 500 code and prints the error to stderr.
func (c *Context) Error(err error) {
c.SetCode(500)
c.WriteString("Internal Server Error")
fmt.Fprintln(os.Stderr, err)
c.reportError(err)
}

// WriteString writes s to the response. We provide WriteString and not Write
Expand Down Expand Up @@ -204,3 +212,23 @@ func (c *Context) IP() net.IP {
c.ip = ip
return ip
}

// Session retrieves the Session related to this context.
func (c *Context) Session() *models.Session {
if c.sessCached {
return c.sess
}
c.sessCached = true
// hash the authorization header, which contains the key
hash := sha256.Sum256(c.ctx.Request.Header.Peek("Authorization"))
encoded := hex.EncodeToString(hash[:])
// find the session in the db
sess, err := c.DB.Session(encoded)
if err != nil {
c.reportError(err)
return nil
}
// cache it
c.sess = sess
return sess
}

0 comments on commit 34593de

Please sign in to comment.