Skip to content

Commit 90a5c6a

Browse files
committed
Initial implementation of getBasicAuth, a *Context helper method
Fixed implementation Added extra error checking
1 parent 673c0e6 commit 90a5c6a

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

helpers.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ package web
22

33
import (
44
"bytes"
5+
"encoding/base64"
6+
"errors"
57
"net/http"
68
"net/url"
79
"os"
@@ -88,3 +90,22 @@ func NewCookie(name string, value string, age int64) *http.Cookie {
8890
}
8991
return &http.Cookie{Name: name, Value: value, Expires: utctime}
9092
}
93+
94+
// GetBasicAuth is a helper method of *Context that returns the decoded
95+
// user and password from the *Context's authorization header
96+
func (ctx *Context) GetBasicAuth() (string, string, error) {
97+
authHeader := ctx.Request.Header["Authorization"][0]
98+
authString := strings.Split(string(authHeader), " ")
99+
if authString[0] != "Basic" {
100+
return "", "", errors.New("Not Basic Authentication")
101+
}
102+
decodedAuth, err := base64.StdEncoding.DecodeString(authString[1])
103+
if err != nil {
104+
return "", "", err
105+
}
106+
authSlice := strings.Split(string(decodedAuth), ":")
107+
if len(authSlice) != 2 {
108+
return "", "", errors.New("Error delimiting authString into username/password. Malformed input: " + authString[1])
109+
}
110+
return authSlice[0], authSlice[1], nil
111+
}

0 commit comments

Comments
 (0)