1
0
mirror of https://github.com/volatiletech/authboss.git synced 2025-02-03 13:21:22 +02:00

Add a method to pick attributes from a context.

This commit is contained in:
Aaron 2015-01-28 00:32:28 -08:00
parent c1670a041f
commit 58e2f1f355
2 changed files with 66 additions and 0 deletions

View File

@ -2,7 +2,11 @@ package authboss
import (
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
)
// Context provides context for module operations and callbacks. One obvious
@ -104,3 +108,34 @@ func (c *Context) SaveUser(key string, storer Storer) error {
return storer.Put(key, c.User)
}
// Attributes converts the post form values into an attributes map.
func (c *Context) Attributes() (Attributes, error) {
attr := make(Attributes)
for name, values := range c.postFormValues {
if len(values) == 0 {
continue
}
val := values[0]
switch {
case strings.HasSuffix(name, "_int"):
integer, err := strconv.Atoi(val)
if err != nil {
return nil, fmt.Errorf("%q (%q): could not be converted to an integer: %v", name, val, err)
}
attr[strings.TrimRight(name, "_int")] = integer
case strings.HasSuffix(name, "_date"):
date, err := time.Parse(time.RFC3339, val)
if err != nil {
return nil, fmt.Errorf("%q (%q): could not be converted to a datetime: %v", name, val, err)
}
attr[strings.TrimRight(name, "_date")] = date.UTC()
default:
attr[name] = val
}
}
return attr, nil
}

View File

@ -4,6 +4,7 @@ import (
"bytes"
"net/http"
"testing"
"time"
)
func TestContext_PutGet(t *testing.T) {
@ -85,3 +86,33 @@ func TestContext_LoadUser(t *testing.T) {
}
}
}
func TestContext_Attributes(t *testing.T) {
now := time.Now().UTC()
ctx := NewContext()
ctx.postFormValues = map[string][]string{
"a": []string{"a", "1"},
"b_int": []string{"5", "hello"},
"wildcard": nil,
"c_date": []string{now.Format(time.RFC3339)},
}
attr, err := ctx.Attributes()
if err != nil {
t.Error(err)
}
if got := attr["a"].(string); got != "a" {
t.Error("a's value is wrong:", got)
}
if got := attr["b"].(int); got != 5 {
t.Error("b's value is wrong:", got)
}
if got := attr["c"].(time.Time); got.Unix() != now.Unix() {
t.Error("c's value is wrong:", now, got)
}
if _, ok := attr["wildcard"]; ok {
t.Error("We don't need totally empty fields.")
}
}