summaryrefslogtreecommitdiff
path: root/app/controllers/utilities.go
blob: 2eae775c97ac4d7a3ddb7779fe7cc1368ed421a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package controllers

import (
	"crypto/md5"
	"fmt"
	"github.com/garyburd/redigo/redis"
	"github.com/tanema/revel_mailer"
	"golang.org/x/crypto/bcrypt"
	"io"
	"io/ioutil"
	"math/rand"
	"net/http"
	"time"
)

// Returns the content of a webpage as string
func Get(url string) (string, error) {
	response, err := http.Get(url)
	if err != nil {
		return "Get request failed.", err
	}

	defer response.Body.Close()
	contents, err := ioutil.ReadAll(response.Body)
	if er != nil {
		return "Reading body failed.", err
	}

	return string(contents), nil
}

// Hashs and returns a string (md5)
func Hash(content string) string {
	h := md5.New()
	io.WriteString(h, content)
	hash := fmt.Sprintf("%x", h.Sum(nil))

	return hash
}

// Creates a random string
func RandomKey() string {
	letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
	key := make([]rune, 40)
	for i := range key {
		key[i] = letters[rand.Intn(len(letters))]
	}

	return string(key)
}

var pool = newPool()

// Creates a pool with connections to Redis
func newPool() *redis.Pool {
	return &redis.Pool{
		MaxIdle:     3,
		IdleTimeout: 240 * time.Second,
		Dial: func() (redis.Conn, error) {
			//c, err := redis.Dial("tcp", ":6379")
			if revel.Config.Bool("cache.redis") {
				// If we use redis as cache we reuse the config part
				c, err := redis.Dial("tcp", revel.Config.String("cache.hosts"))
			} else {
				// Otherwise we use our own configuration
				c, err := redis.Dial("tcp", revel.Config.String("redis.server")+":"+revel.Config.String("redis.port"))
			}
			if err != nil {
				return nil, err
			}
			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}
}

// Hashs password with bcrypt and returns the string
func HashPassword(password string) (string, error) {
	if password == "" {
		return nil, nil
	}
	p := []byte(password)
	hash, err := bcrypt.GenerateFromPassword(p, 10)
	if err != nil {
		return nil, err
	}
	return string(hash)
}

// Verify password and hash
func VerifyPassword(password, hash string) (bool, error) {
	err := bcrypt.CompareHashAndPassword(hash, password)
	if err != nil {
		return false, err
	}
	return true, nil
}