Merge branch 'emailing'

This commit is contained in:
Torkel Ödegaard
2015-06-08 17:57:33 +02:00
43 changed files with 1043 additions and 53 deletions

View File

@@ -175,6 +175,20 @@ header_name = X-WEBAUTH-USER
header_property = username
auto_sign_up = true
#################################### SMTP / Emailing ##########################
[smtp]
enabled = false
host = localhost:25
user =
password =
cert_file =
key_file =
skip_verify = false
from_address = admin@grafana.localhost
[emails]
welcome_email_on_sign_up = false
#################################### Logging ##########################
[log]
# Either "console", "file", default is "console"

View File

@@ -174,6 +174,20 @@
;header_property = username
;auto_sign_up = true
#################################### SMTP / Emailing ##########################
[smtp]
;enabled = false
;host = localhost:25
;user =
;password =
;cert_file =
;key_file =
;skip_verify = false
;from_address = admin@grafana.localhost
[emails]
;welcome_email_on_sign_up = false
#################################### Logging ##########################
[log]
# Either "console", "file", default is "console"

View File

@@ -0,0 +1,13 @@
FROM centos:centos7
MAINTAINER Przemyslaw Ozgo <linux@ozgo.info>
RUN \
yum update -y && \
yum install -y net-snmp net-snmp-utils && \
yum clean all
COPY bootstrap.sh /tmp/bootstrap.sh
EXPOSE 161
ENTRYPOINT ["/tmp/bootstrap.sh"]

27
docker/blocks/smtp/bootstrap.sh Executable file
View File

@@ -0,0 +1,27 @@
#!/bin/sh
set -u
# User params
USER_PARAMS=$@
# Internal params
RUN_CMD="snmpd -f ${USER_PARAMS}"
#######################################
# Echo/log function
# Arguments:
# String: value to log
#######################################
log() {
if [[ "$@" ]]; then echo "[`date +'%Y-%m-%d %T'`] $@";
else echo; fi
}
# Launch
log $RUN_CMD
$RUN_CMD
# Exit immidiately in case of any errors or when we have interactive terminal
if [[ $? != 0 ]] || test -t 0; then exit $?; fi
log

4
docker/blocks/smtp/fig Normal file
View File

@@ -0,0 +1,4 @@
snmpd:
build: blocks/snmpd
ports:
- "161:161"

View File

@@ -14,8 +14,9 @@ import (
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/metrics"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/search"
"github.com/grafana/grafana/pkg/services/eventpublisher"
"github.com/grafana/grafana/pkg/services/notifications"
"github.com/grafana/grafana/pkg/services/search"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/social"
@@ -57,6 +58,10 @@ func main() {
eventpublisher.Init()
plugins.Init()
if err := notifications.Init(); err != nil {
log.Fatal(3, "Notification service failed to initialize", err)
}
if setting.ReportingEnabled {
go metrics.StartUsageReportLoop()
}

View File

@@ -41,6 +41,13 @@ func Register(r *macaron.Macaron) {
r.Get("/signup", Index)
r.Post("/api/user/signup", bind(m.CreateUserCommand{}), SignUp)
// reset password
r.Get("/user/password/send-reset-email", Index)
r.Get("/user/password/reset", Index)
r.Post("/api/user/password/send-reset-email", bind(dtos.SendResetPasswordEmailForm{}), wrap(SendResetPasswordEmail))
r.Post("/api/user/password/reset", bind(dtos.ResetUserPasswordForm{}), wrap(ResetPassword))
// dashboard snapshots
r.Post("/api/snapshots/", bind(m.CreateDashboardSnapshotCommand{}), CreateDashboardSnapshot)
r.Get("/dashboard/snapshot/*", Index)

View File

@@ -10,7 +10,7 @@ import (
"github.com/grafana/grafana/pkg/metrics"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/search"
"github.com/grafana/grafana/pkg/services/search"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)

View File

@@ -27,3 +27,13 @@ type AdminUserListItem struct {
Login string `json:"login"`
IsGrafanaAdmin bool `json:"isGrafanaAdmin"`
}
type SendResetPasswordEmailForm struct {
UserOrEmail string `json:"userOrEmail" binding:"Required"`
}
type ResetUserPasswordForm struct {
Code string `json:"code"`
NewPassword string `json:"newPassword"`
ConfirmPassword string `json:"confirmPassword"`
}

49
pkg/api/password.go Normal file
View File

@@ -0,0 +1,49 @@
package api
import (
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/util"
)
func SendResetPasswordEmail(c *middleware.Context, form dtos.SendResetPasswordEmailForm) Response {
userQuery := m.GetUserByLoginQuery{LoginOrEmail: form.UserOrEmail}
if err := bus.Dispatch(&userQuery); err != nil {
return ApiError(404, "User does not exist", err)
}
emailCmd := m.SendResetPasswordEmailCommand{User: userQuery.Result}
if err := bus.Dispatch(&emailCmd); err != nil {
return ApiError(500, "Failed to send email", err)
}
return ApiSuccess("Email sent")
}
func ResetPassword(c *middleware.Context, form dtos.ResetUserPasswordForm) Response {
query := m.ValidateResetPasswordCodeQuery{Code: form.Code}
if err := bus.Dispatch(&query); err != nil {
if err == m.ErrInvalidEmailCode {
return ApiError(400, "Invalid or expired reset password code", nil)
}
return ApiError(500, "Unknown error validating email code", err)
}
if form.NewPassword != form.ConfirmPassword {
return ApiError(400, "Passwords do not match", nil)
}
cmd := m.ChangeUserPasswordCommand{}
cmd.UserId = query.Result.Id
cmd.NewPassword = util.EncodePassword(form.NewPassword, query.Result.Salt)
if err := bus.Dispatch(&cmd); err != nil {
return ApiError(500, "Failed to change user password", err)
}
return ApiSuccess("User password changed")
}

View File

@@ -3,7 +3,7 @@ package api
import (
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/middleware"
"github.com/grafana/grafana/pkg/search"
"github.com/grafana/grafana/pkg/services/search"
)
func Search(c *middleware.Context) {

View File

@@ -2,6 +2,7 @@ package api
import (
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/events"
"github.com/grafana/grafana/pkg/metrics"
"github.com/grafana/grafana/pkg/middleware"
m "github.com/grafana/grafana/pkg/models"
@@ -24,6 +25,13 @@ func SignUp(c *middleware.Context, cmd m.CreateUserCommand) {
user := cmd.Result
bus.Publish(&events.UserSignedUp{
Id: user.Id,
Name: user.Name,
Email: user.Email,
Login: user.Login,
})
loginUserWithUser(&user, c)
c.JsonOK("User created and logged in")

View File

@@ -70,6 +70,14 @@ type UserCreated struct {
Email string `json:"email"`
}
type UserSignedUp struct {
Timestamp time.Time `json:"timestamp"`
Id int64 `json:"id"`
Name string `json:"name"`
Login string `json:"login"`
Email string `json:"email"`
}
type UserUpdated struct {
Timestamp time.Time `json:"timestamp"`
Id int64 `json:"id"`

22
pkg/models/emails.go Normal file
View File

@@ -0,0 +1,22 @@
package models
import "errors"
var ErrInvalidEmailCode = errors.New("Invalid or expired email code")
type SendEmailCommand struct {
To []string
Template string
Data map[string]interface{}
Massive bool
Info string
}
type SendResetPasswordEmailCommand struct {
User *User
}
type ValidateResetPasswordCodeQuery struct {
Code string
Result *User
}

View File

@@ -30,6 +30,16 @@ type User struct {
Updated time.Time
}
func (u *User) NameOrFallback() string {
if u.Name != "" {
return u.Name
} else if u.Login != "" {
return u.Login
} else {
return u.Email
}
}
// ---------------------
// COMMANDS

View File

@@ -0,0 +1,98 @@
package notifications
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"time"
"github.com/Unknwon/com"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
)
const timeLimitCodeLength = 12 + 6 + 40
// create a time limit code
// code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
func createTimeLimitCode(data string, minutes int, startInf interface{}) string {
format := "200601021504"
var start, end time.Time
var startStr, endStr string
if startInf == nil {
// Use now time create code
start = time.Now()
startStr = start.Format(format)
} else {
// use start string create code
startStr = startInf.(string)
start, _ = time.ParseInLocation(format, startStr, time.Local)
startStr = start.Format(format)
}
end = start.Add(time.Minute * time.Duration(minutes))
endStr = end.Format(format)
// create sha1 encode string
sh := sha1.New()
sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
encoded := hex.EncodeToString(sh.Sum(nil))
code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
return code
}
// verify time limit code
func validateUserEmailCode(user *m.User, code string) bool {
if len(code) <= 18 {
return false
}
minutes := setting.EmailCodeValidMinutes
code = code[:timeLimitCodeLength]
// split code
start := code[:12]
lives := code[12:18]
if d, err := com.StrTo(lives).Int(); err == nil {
minutes = d
}
// right active code
data := com.ToStr(user.Id) + user.Email + user.Login + user.Password + user.Rands
retCode := createTimeLimitCode(data, minutes, start)
fmt.Printf("code : %s\ncode2: %s", retCode, code)
if retCode == code && minutes > 0 {
// check time is expired or not
before, _ := time.ParseInLocation("200601021504", start, time.Local)
now := time.Now()
if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
return true
}
}
return false
}
func getLoginForEmailCode(code string) string {
if len(code) <= timeLimitCodeLength {
return ""
}
// use tail hex username query user
hexStr := code[timeLimitCodeLength:]
b, _ := hex.DecodeString(hexStr)
return string(b)
}
func createUserEmailCode(u *m.User, startInf interface{}) string {
minutes := setting.EmailCodeValidMinutes
data := com.ToStr(u.Id) + u.Email + u.Login + u.Password + u.Rands
code := createTimeLimitCode(data, minutes, startInf)
// add tail hex username
code += hex.EncodeToString([]byte(u.Login))
return code
}

View File

@@ -0,0 +1,35 @@
package notifications
import (
"testing"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
func TestEmailCodes(t *testing.T) {
Convey("When generating code", t, func() {
setting.EmailCodeValidMinutes = 120
user := &m.User{Id: 10, Email: "t@a.com", Login: "asd", Password: "1", Rands: "2"}
code := createUserEmailCode(user, nil)
Convey("getLoginForCode should return login", func() {
login := getLoginForEmailCode(code)
So(login, ShouldEqual, "asd")
})
Convey("Can verify valid code", func() {
So(validateUserEmailCode(user, code), ShouldBeTrue)
})
Convey("Cannot verify in-valid code", func() {
code = "ASD"
So(validateUserEmailCode(user, code), ShouldBeFalse)
})
})
}

View File

@@ -0,0 +1,33 @@
package notifications
import (
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
)
type Message struct {
To []string
From string
Subject string
Body string
Massive bool
Info string
}
// create mail content
func (m *Message) Content() string {
contentType := "text/html; charset=UTF-8"
content := "From: " + m.From + "\r\nSubject: " + m.Subject + "\r\nContent-Type: " + contentType + "\r\n\r\n" + m.Body
return content
}
func setDefaultTemplateData(data map[string]interface{}, u *m.User) {
data["AppUrl"] = setting.AppUrl
data["BuildVersion"] = setting.BuildVersion
data["BuildStamp"] = setting.BuildStamp
data["EmailCodeValidHours"] = setting.EmailCodeValidMinutes / 60
data["Subject"] = map[string]interface{}{}
if u != nil {
data["Name"] = u.NameOrFallback()
}
}

View File

@@ -0,0 +1,186 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package notifications
import (
"crypto/tls"
"fmt"
"net"
"net/mail"
"net/smtp"
"os"
"strings"
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/setting"
)
var mailQueue chan *Message
func initMailQueue() {
mailQueue = make(chan *Message, 10)
go processMailQueue()
}
func processMailQueue() {
for {
select {
case msg := <-mailQueue:
num, err := buildAndSend(msg)
tos := strings.Join(msg.To, "; ")
info := ""
if err != nil {
if len(msg.Info) > 0 {
info = ", info: " + msg.Info
}
log.Error(4, fmt.Sprintf("Async sent email %d succeed, not send emails: %s%s err: %s", num, tos, info, err))
} else {
log.Trace(fmt.Sprintf("Async sent email %d succeed, sent emails: %s%s", num, tos, info))
}
}
}
}
var addToMailQueue = func(msg *Message) {
mailQueue <- msg
}
func sendToSmtpServer(recipients []string, msgContent []byte) error {
host, port, err := net.SplitHostPort(setting.Smtp.Host)
if err != nil {
return err
}
tlsconfig := &tls.Config{
InsecureSkipVerify: setting.Smtp.SkipVerify,
ServerName: host,
}
if setting.Smtp.CertFile != "" {
cert, err := tls.LoadX509KeyPair(setting.Smtp.CertFile, setting.Smtp.KeyFile)
if err != nil {
return err
}
tlsconfig.Certificates = []tls.Certificate{cert}
}
conn, err := net.Dial("tcp", net.JoinHostPort(host, port))
if err != nil {
return err
}
defer conn.Close()
isSecureConn := false
// Start TLS directly if the port ends with 465 (SMTPS protocol)
if strings.HasSuffix(port, "465") {
conn = tls.Client(conn, tlsconfig)
isSecureConn = true
}
client, err := smtp.NewClient(conn, host)
if err != nil {
return err
}
hostname, err := os.Hostname()
if err != nil {
return err
}
if err = client.Hello(hostname); err != nil {
return err
}
// If not using SMTPS, alway use STARTTLS if available
hasStartTLS, _ := client.Extension("STARTTLS")
if !isSecureConn && hasStartTLS {
if err = client.StartTLS(tlsconfig); err != nil {
return err
}
}
canAuth, options := client.Extension("AUTH")
if canAuth && len(setting.Smtp.User) > 0 {
var auth smtp.Auth
if strings.Contains(options, "CRAM-MD5") {
auth = smtp.CRAMMD5Auth(setting.Smtp.User, setting.Smtp.Password)
} else if strings.Contains(options, "PLAIN") {
auth = smtp.PlainAuth("", setting.Smtp.User, setting.Smtp.Password, host)
}
if auth != nil {
if err = client.Auth(auth); err != nil {
return err
}
}
}
if fromAddress, err := mail.ParseAddress(setting.Smtp.FromAddress); err != nil {
return err
} else {
if err = client.Mail(fromAddress.Address); err != nil {
return err
}
}
for _, rec := range recipients {
if err = client.Rcpt(rec); err != nil {
return err
}
}
w, err := client.Data()
if err != nil {
return err
}
if _, err = w.Write([]byte(msgContent)); err != nil {
return err
}
if err = w.Close(); err != nil {
return err
}
return client.Quit()
}
func buildAndSend(msg *Message) (int, error) {
log.Trace("Sending mails to: %s", strings.Join(msg.To, "; "))
// get message body
content := msg.Content()
if len(msg.To) == 0 {
return 0, fmt.Errorf("empty receive emails")
} else if len(msg.Body) == 0 {
return 0, fmt.Errorf("empty email body")
}
if msg.Massive {
// send mail to multiple emails one by one
num := 0
for _, to := range msg.To {
body := []byte("To: " + to + "\r\n" + content)
err := sendToSmtpServer([]string{to}, body)
if err != nil {
return num, err
}
num++
}
return num, nil
} else {
body := []byte("To: " + strings.Join(msg.To, ";") + "\r\n" + content)
// send to multiple emails in one message
err := sendToSmtpServer(msg.To, body)
if err != nil {
return 0, err
} else {
return 1, nil
}
}
}

View File

@@ -0,0 +1,125 @@
package notifications
import (
"bytes"
"errors"
"html/template"
"path/filepath"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/events"
"github.com/grafana/grafana/pkg/log"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
var mailTemplates *template.Template
var tmplResetPassword = "reset_password.html"
var tmplWelcomeOnSignUp = "welcome_on_signup.html"
func Init() error {
initMailQueue()
bus.AddHandler("email", sendResetPasswordEmail)
bus.AddHandler("email", validateResetPasswordCode)
bus.AddHandler("email", sendEmailCommandHandler)
bus.AddEventListener(userSignedUpHandler)
mailTemplates = template.New("name")
mailTemplates.Funcs(template.FuncMap{
"Subject": subjectTemplateFunc,
})
templatePattern := filepath.Join(setting.StaticRootPath, "emails/*.html")
_, err := mailTemplates.ParseGlob(templatePattern)
if err != nil {
return err
}
if !util.IsEmail(setting.Smtp.FromAddress) {
return errors.New("Invalid email address for smpt from_adress config")
}
if setting.EmailCodeValidMinutes == 0 {
setting.EmailCodeValidMinutes = 120
}
return nil
}
func subjectTemplateFunc(obj map[string]interface{}, value string) string {
obj["value"] = value
return ""
}
func sendEmailCommandHandler(cmd *m.SendEmailCommand) error {
if !setting.Smtp.Enabled {
return errors.New("Grafana mailing/smtp options not configured, contact your Grafana admin")
}
var buffer bytes.Buffer
data := cmd.Data
if data == nil {
data = make(map[string]interface{}, 10)
}
setDefaultTemplateData(data, nil)
mailTemplates.ExecuteTemplate(&buffer, cmd.Template, data)
addToMailQueue(&Message{
To: cmd.To,
From: setting.Smtp.FromAddress,
Subject: data["Subject"].(map[string]interface{})["value"].(string),
Body: buffer.String(),
})
return nil
}
func sendResetPasswordEmail(cmd *m.SendResetPasswordEmailCommand) error {
return sendEmailCommandHandler(&m.SendEmailCommand{
To: []string{cmd.User.Email},
Template: tmplResetPassword,
Data: map[string]interface{}{
"Code": createUserEmailCode(cmd.User, nil),
"Name": cmd.User.NameOrFallback(),
},
})
}
func validateResetPasswordCode(query *m.ValidateResetPasswordCodeQuery) error {
login := getLoginForEmailCode(query.Code)
if login == "" {
return m.ErrInvalidEmailCode
}
userQuery := m.GetUserByLoginQuery{LoginOrEmail: login}
if err := bus.Dispatch(&userQuery); err != nil {
return err
}
if !validateUserEmailCode(userQuery.Result, query.Code) {
return m.ErrInvalidEmailCode
}
query.Result = userQuery.Result
return nil
}
func userSignedUpHandler(evt *events.UserSignedUp) error {
log.Info("User signed up: %s, send_option: %s", evt.Email, setting.Smtp.SendWelcomeEmailOnSignUp)
if evt.Email == "" || !setting.Smtp.SendWelcomeEmailOnSignUp {
return nil
}
return sendEmailCommandHandler(&m.SendEmailCommand{
To: []string{evt.Email},
Template: tmplWelcomeOnSignUp,
Data: map[string]interface{}{
"Name": evt.Login,
},
})
}

View File

@@ -0,0 +1,36 @@
package notifications
import (
"testing"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
)
func TestNotifications(t *testing.T) {
Convey("Given the notifications service", t, func() {
bus.ClearBusHandlers()
setting.StaticRootPath = "../../../public/"
setting.Smtp.FromAddress = "from@address.com"
err := Init()
So(err, ShouldBeNil)
var sentMsg *Message
addToMailQueue = func(msg *Message) {
sentMsg = msg
}
Convey("When sending reset email password", func() {
sendResetPasswordEmail(&m.SendResetPasswordEmailCommand{User: &m.User{Email: "asd@asd.com"}})
So(sentMsg.Body, ShouldContainSubstring, "body")
So(sentMsg.Subject, ShouldEqual, "Reset your Grafana password")
So(sentMsg.Body, ShouldNotContainSubstring, "Subject")
})
})
}

View File

@@ -11,7 +11,7 @@ import (
func TestSearch(t *testing.T) {
Convey("Given search query", t, func() {
jsonDashIndex = NewJsonDashIndex("../../public/dashboards/")
jsonDashIndex = NewJsonDashIndex("../../../public/dashboards/")
query := Query{Limit: 2000}
bus.AddHandler("test", func(query *FindPersistedDashboardsQuery) error {

View File

@@ -9,7 +9,7 @@ import (
func TestJsonDashIndex(t *testing.T) {
Convey("Given the json dash index", t, func() {
index := NewJsonDashIndex("../../public/dashboards/")
index := NewJsonDashIndex("../../../public/dashboards/")
Convey("Should be able to update index", func() {
err := index.updateIndex()

View File

@@ -8,7 +8,7 @@ import (
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/metrics"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/search"
"github.com/grafana/grafana/pkg/services/search"
)
func init() {

View File

@@ -6,7 +6,7 @@ import (
. "github.com/smartystreets/goconvey/convey"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/search"
"github.com/grafana/grafana/pkg/services/search"
)
func insertTestDashboard(title string, orgId int64, tags ...interface{}) *m.Dashboard {

View File

@@ -38,7 +38,6 @@ const (
var (
// App settings.
Env string = DEV
AppName string
AppUrl string
AppSubUrl string
@@ -68,11 +67,12 @@ var (
EnforceDomain bool
// Security settings.
SecretKey string
LogInRememberDays int
CookieUserName string
CookieRememberName string
DisableGravatar bool
SecretKey string
LogInRememberDays int
CookieUserName string
CookieRememberName string
DisableGravatar bool
EmailCodeValidMinutes int
// User settings
AllowUserSignUp bool
@@ -114,6 +114,9 @@ var (
ReportingEnabled bool
GoogleAnalyticsId string
// SMTP email settings
Smtp SmtpSettings
)
type CommandLineArgs struct {
@@ -347,7 +350,6 @@ func NewConfigContext(args *CommandLineArgs) {
setHomePath(args)
loadConfiguration(args)
AppName = Cfg.Section("").Key("app_name").MustString("Grafana")
Env = Cfg.Section("").Key("app_mode").MustString("development")
server := Cfg.Section("server")
@@ -407,6 +409,7 @@ func NewConfigContext(args *CommandLineArgs) {
GoogleAnalyticsId = analytics.Key("google_analytics_ua_id").String()
readSessionConfig()
readSmtpSettings()
}
func readSessionConfig() {

View File

@@ -0,0 +1,29 @@
package setting
type SmtpSettings struct {
Enabled bool
Host string
User string
Password string
CertFile string
KeyFile string
FromAddress string
SkipVerify bool
SendWelcomeEmailOnSignUp bool
}
func readSmtpSettings() {
sec := Cfg.Section("smtp")
Smtp.Enabled = sec.Key("enabled").MustBool(false)
Smtp.Host = sec.Key("host").String()
Smtp.User = sec.Key("user").String()
Smtp.Password = sec.Key("password").String()
Smtp.CertFile = sec.Key("cert_file").String()
Smtp.KeyFile = sec.Key("key_file").String()
Smtp.FromAddress = sec.Key("from_address").String()
Smtp.SkipVerify = sec.Key("skip_verify").MustBool(false)
emails := Cfg.Section("emails")
Smtp.SendWelcomeEmailOnSignUp = emails.Key("welcome_email_on_sign_up").MustBool(false)
}

View File

@@ -15,7 +15,6 @@ func TestLoadingSettings(t *testing.T) {
Convey("Given the default ini files", func() {
NewConfigContext(&CommandLineArgs{HomePath: "../../"})
So(AppName, ShouldEqual, "Grafana")
So(AdminUser, ShouldEqual, "admin")
})

18
pkg/util/validation.go Normal file
View File

@@ -0,0 +1,18 @@
package util
import (
"regexp"
"strings"
)
const (
emailRegexPattern string = "^(((([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$"
)
var (
regexEmail = regexp.MustCompile(emailRegexPattern)
)
func IsEmail(str string) bool {
return regexEmail.MatchString(strings.ToLower(str))
}

View File

@@ -6,6 +6,7 @@ define([
'./inspectCtrl',
'./jsonEditorCtrl',
'./loginCtrl',
'./resetPasswordCtrl',
'./sidemenuCtrl',
'./errorCtrl',
], function () {});

View File

@@ -21,13 +21,10 @@ function (angular, config) {
$scope.disableUserSignUp = config.disableUserSignUp;
$scope.loginMode = true;
$scope.submitBtnClass = 'btn-inverse';
$scope.submitBtnText = 'Log in';
$scope.strengthClass = '';
$scope.init = function() {
$scope.$watch("loginMode", $scope.loginModeChanged);
$scope.passwordChanged();
var params = $location.search();
if (params.failedMsg) {
@@ -56,27 +53,6 @@ function (angular, config) {
$scope.submitBtnText = newValue ? 'Log in' : 'Sign up';
};
$scope.passwordChanged = function(newValue) {
if (!newValue) {
$scope.strengthText = "";
$scope.strengthClass = "hidden";
return;
}
if (newValue.length < 4) {
$scope.strengthText = "strength: weak sauce.";
$scope.strengthClass = "password-strength-bad";
return;
}
if (newValue.length <= 8) {
$scope.strengthText = "strength: you can do better.";
$scope.strengthClass = "password-strength-ok";
return;
}
$scope.strengthText = "strength: strong like a bull.";
$scope.strengthClass = "password-strength-good";
};
$scope.signUp = function() {
if (!$scope.loginForm.$valid) {
return;

View File

@@ -0,0 +1,45 @@
define([
'angular',
],
function (angular) {
'use strict';
var module = angular.module('grafana.controllers');
module.controller('ResetPasswordCtrl', function($scope, contextSrv, backendSrv, $location) {
contextSrv.sidemenu = false;
$scope.formModel = {};
$scope.mode = 'send';
var params = $location.search();
if (params.code) {
$scope.mode = 'reset';
$scope.formModel.code = params.code;
}
$scope.sendResetEmail = function() {
if (!$scope.sendResetForm.$valid) {
return;
}
backendSrv.post('/api/user/password/send-reset-email', $scope.formModel).then(function() {
$scope.mode = 'email-sent';
});
};
$scope.submitReset = function() {
if (!$scope.resetForm.$valid) { return; }
if ($scope.formModel.newPassword !== $scope.formModel.confirmPassword) {
$scope.appEvent('alert-warning', ['New passwords do not match', '']);
return;
}
backendSrv.post('/api/user/password/reset', $scope.formModel).then(function() {
$location.path('login');
});
};
});
});

View File

@@ -18,4 +18,5 @@ define([
'./topnav',
'./giveFocus',
'./annotationTooltip',
'./passwordStrenght',
], function () {});

View File

@@ -0,0 +1,47 @@
define([
'angular',
],
function (angular) {
'use strict';
angular
.module('grafana.directives')
.directive('passwordStrength', function() {
var template = '<div class="password-strength small" ng-if="!loginMode" ng-class="strengthClass">' +
'<em>{{strengthText}}</em>' +
'</div>';
return {
template: template,
scope: {
password: "=",
},
link: function($scope) {
$scope.strengthClass = '';
function passwordChanged(newValue) {
if (!newValue) {
$scope.strengthText = "";
$scope.strengthClass = "hidden";
return;
}
if (newValue.length < 4) {
$scope.strengthText = "strength: weak sauce.";
$scope.strengthClass = "password-strength-bad";
return;
}
if (newValue.length <= 8) {
$scope.strengthText = "strength: you can do better.";
$scope.strengthClass = "password-strength-ok";
return;
}
$scope.strengthText = "strength: strong like a bull.";
$scope.strengthClass = "password-strength-good";
}
$scope.$watch("password", passwordChanged);
}
};
});
});

View File

@@ -42,7 +42,7 @@
<div class="tight-form" ng-if="!loginMode">
<ul class="tight-form-list">
<li class="tight-form-item" style="width: 80px">
<li class="tight-form-item" style="width: 79px">
<strong>Email</strong>
</li>
<li>
@@ -54,24 +54,22 @@
<div class="tight-form" ng-if="!loginMode">
<ul class="tight-form-list">
<li class="tight-form-item" style="width: 80px">
<li class="tight-form-item" style="width: 79px">
<strong>Password</strong>
</li>
<li>
<input type="password" class="tight-form-input last" watch-change="passwordChanged(inputValue)" ng-minlength="4" required ng-model='formModel.password' placeholder="password" style="width: 253px">
<input type="password" class="tight-form-input last" watch-change="formModel.password = inputValue;" ng-minlength="4" required ng-model='formModel.password' placeholder="password" style="width: 253px">
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="password-strength small" ng-if="!loginMode" ng-class="strengthClass">
<em>{{strengthText}}</em>
<div ng-if="!loginMode" style="margin-left: 97px; width: 254px;">
<password-strength password="formModel.password"></password-strength>
</div>
<div class="login-submit-button-row">
<button type="submit" class="btn" ng-click="submit();"
ng-class="{'btn-inverse': !loginForm.$valid, 'btn-primary': loginForm.$valid}">
<button type="submit" class="btn" ng-click="submit();" ng-class="{'btn-inverse': !loginForm.$valid, 'btn-primary': loginForm.$valid}">
{{submitBtnText}}
</button>
</div>
@@ -91,7 +89,15 @@
</div>
</div>
<div class="row" style="margin-top: 100px">
<div class="row" style="margin-top: 40px">
<div class="text-center">
<a href="user/password/send-reset-email">
Forgot your password?
</a>
</div>
</div>
<div class="row" style="margin-top: 50px">
<div class="version-footer text-center small">
Grafana version: {{buildInfo.version}}, commit: {{buildInfo.commit}},
build date: {{buildInfo.buildstamp | date: 'yyyy-MM-dd HH:mm:ss' }}

View File

@@ -0,0 +1,90 @@
<div class="container">
<div class="login-box">
<div class="login-box-logo">
<a href="login">
<img src="img/logo_transparent_200x75.png">
</a>
</div>
<div class="login-inner-box">
<div class="login-tab-header">
<button class="btn-login-tab" class="active">
Reset password
</button>
</div>
<form name="sendResetForm" class="login-form" ng-show="mode === 'send'">
<div class="tight-form last">
<ul class="tight-form-list">
<li class="tight-form-item" style="width: 78px">
<strong>User</strong>
</li>
<li>
<input type="text" name="username" class="tight-form-input last" required ng-model='formModel.userOrEmail' placeholder="email or username" style="width: 253px">
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="login-submit-button-row">
<button type="submit" class="btn" ng-click="sendResetEmail();" ng-class="{'btn-inverse': !sendResetForm.$valid, 'btn-primary': sendResetForm.$valid}">
Send reset instructions
</button>
</div>
</form>
<h5 ng-if="mode === 'email-sent'" style="text-align: center; padding: 20px;">
An email with a reset link as been sent to the email address, you should receive it shortly.
</h5>
<form name="resetForm" class="login-form" ng-show="mode === 'reset'">
<div class="tight-form">
<ul class="tight-form-list">
<li class="tight-form-item" style="width: 125px">
<strong>New Password</strong>
</li>
<li>
<input type="password" name="NewPassword" class="tight-form-input last" required ng-minlength="4" ng-model='formModel.newPassword' placeholder="password" style="width: 207px" watch-change="formModel.newPassword = inputValue;">
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="tight-form last">
<ul class="tight-form-list">
<li class="tight-form-item" style="width: 125px">
<strong>Confirm Password</strong>
</li>
<li>
<input type="password" name="ConfirmPassword" class="tight-form-input last" required ng-minlength="4" ng-model='formModel.confirmPassword' placeholder="confirm password" style="width: 207px">
</li>
</ul>
<div class="clearfix"></div>
</div>
<div style="margin-left: 141px; width: 207px;">
<password-strength password="formModel.newPassword"></password-strength>
</div>
<div class="login-submit-button-row">
<button type="submit" class="btn" ng-click="submitReset();" ng-class="{'btn-inverse': !resetForm.$valid, 'btn-primary': resetForm.$valid}">
Reset Password
</button>
</div>
</form>
<div class="clearfix"></div>
</div>
<div class="row" style="margin-top: 40px">
<div class="text-center">
<a href="login">
Back to login
</a>
</div>
</div>
</div>
</div>

View File

@@ -97,6 +97,14 @@ define([
templateUrl: 'app/partials/login.html',
controller : 'LoginCtrl',
})
.when('/user/password/send-reset-email', {
templateUrl: 'app/partials/reset_password.html',
controller : 'ResetPasswordCtrl',
})
.when('/user/password/reset', {
templateUrl: 'app/partials/reset_password.html',
controller : 'ResetPasswordCtrl',
})
.otherwise({
templateUrl: 'app/partials/error.html',
controller: 'ErrorCtrl'

View File

@@ -50,19 +50,18 @@
.password-strength {
display: block;
width: 50px;
width: 15%;
overflow: visible;
white-space: nowrap;
padding-top: 3px;
margin-left: 97px;
color: darken(@textColor, 20%);
border-top: 3px solid @red;
&.password-strength-ok {
width: 170px;
width: 40%;
border-top: 3px solid lighten(@yellow, 10%);
}
&.password-strength-good {
width: 254px;
width: 100%;
border-top: 3px solid lighten(@green, 10%);
}
}
@@ -74,7 +73,7 @@
padding: 9px 7px;
font-size: 14px;
font-weight: bold;
width: 150px;
min-width: 150px;
display: inline-block;
border: 1px solid lighten(@btnInverseBackground, 10%);
}

View File

@@ -0,0 +1,34 @@
{{Subject .Subject "Reset your Grafana password"}}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{{.Name}}, please reset your password</title>
</head>
<body style="background:#eee;">
<div style="color:#333; font:12px/1.5 Tahoma,Arial,sans-serif;; text-shadow:1px 1px #fff; padding:0; margin:0;">
<div style="width:600px;margin:0 auto; padding:40px 0 20px;">
<div style="border:1px solid #d9d9d9;border-radius:3px; background:#fff; box-shadow: 0px 2px 5px rgba(0, 0, 0,.05); -webkit-box-shadow: 0px 2px 5px rgba(0, 0, 0,.05);">
<div style="padding: 20px 15px;">
<div style="padding:40px 15px;">
<div style="font-size:16px; padding-bottom:30px; font-weight:bold;">
Hi <span style="color: #00BFFF;">{{.Name}}</span>,
</div>
<div style="font-size:14px; padding:0 15px;">
<p style="margin:0;padding:0 0 9px 0;">Please click the following link to reset your password within <b>{{.EmailCodeValidHours}} hours</b>.</p>
<p style="margin:0;padding:0 0 9px 0;">
<a href="{{.AppUrl}}/user/password/reset?code={{.Code}}">{{.AppUrl}}user/password/reset?code={{.Code}}</a>
</p>
<p style="margin:0;padding:0 0 9px 0;">Not working? Try copying and pasting it to your browser.</p>
</div>
</div>
</div>
</div>
<div style="color:#aaa;padding:10px;text-align:center;">
© 2014 <a style="color:#888;text-decoration:none;" target="_blank" href="http://grafana.org">Grafana</a>
</div>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,30 @@
{{Subject .Subject "Welcome to Grafana"}}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{{.Name}} Welcome to Grafana</title>
</head>
<body style="background:#eee;">
<div style="color:#333; font:12px/1.5 Tahoma,Arial,sans-serif;; text-shadow:1px 1px #fff; padding:0; margin:0;">
<div style="width:600px;margin:0 auto; padding:40px 0 20px;">
<div style="border:1px solid #d9d9d9;border-radius:3px; background:#fff; box-shadow: 0px 2px 5px rgba(0, 0, 0,.05); -webkit-box-shadow: 0px 2px 5px rgba(0, 0, 0,.05);">
<div style="padding: 20px 15px;">
<div style="padding:40px 15px;">
<div style="font-size:16px; padding-bottom:30px; font-weight:bold;">
Hi <span style="color: #00BFFF;">{{.Name}}</span>,
</div>
<div style="font-size:14px; padding:0 15px;">
</div>
</div>
</div>
</div>
<div style="color:#aaa;padding:10px;text-align:center;">
© 2014 <a style="color:#888;text-decoration:none;" target="_blank" href="http://grafana.org">Grafana</a>
</div>
</div>
</div>
</body>
</html>