Created
July 10, 2013 06:44
-
-
Save landaire/5963948 to your computer and use it in GitHub Desktop.
HTTP Basic Auth for Revel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package controllers | |
import ( | |
"encoding/base64" | |
"errors" | |
"github.com/robfig/revel" | |
"net/http" | |
"strings" | |
) | |
type Auth struct { | |
*revel.Controller | |
} | |
const ( | |
correctUsername string = "user" | |
correctPassword string = "pass" | |
) | |
func getCredentials(data string) (username, password string, err error) { | |
decodedData, err := base64.StdEncoding.DecodeString(data) | |
if err != nil { | |
return "", "", err | |
} | |
strData := strings.Split(string(decodedData), ":") | |
username = strData[0] | |
password = strData[1] | |
return | |
} | |
func (c Auth) Index() revel.Result { | |
// The auth data is sent in the headers and will have a value of "Basic XXX" where XXX is base64 encoded data | |
if auth := c.Request.Header.Get("Authorization"); auth != "" { | |
// Split up the string to get just the data, then get the credentials | |
username, password, err := getCredentials(strings.Split(auth, " ")[1]) | |
if err != nil { | |
return c.RenderError(err) | |
} | |
if username != correctUsername || password != correctPassword { | |
c.Response.Status = http.StatusUnauthorized | |
c.Response.Out.Header().Set("WWW-Authenticate", `Basic realm="revel"`) | |
return c.RenderError(errors.New("401: Not authorized")) | |
} | |
return c.RenderText("username: %s\npassword: %s", username, password) | |
} else { | |
c.Response.Status = http.StatusUnauthorized | |
c.Response.Out.Header().Set("WWW-Authenticate", `Basic realm="revel"`) | |
return c.RenderError(errors.New("401: Not authorized")) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment