Commit aa4d60c2 by Torkel Ödegaard

Worked on reset password views, refactored out password strength to a reusable directive

parent e40b4620
...@@ -41,6 +41,13 @@ func Register(r *macaron.Macaron) { ...@@ -41,6 +41,13 @@ func Register(r *macaron.Macaron) {
r.Get("/signup", Index) r.Get("/signup", Index)
r.Post("/api/user/signup", bind(m.CreateUserCommand{}), SignUp) 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", wrap(ViewResetPasswordForm))
// dashboard snapshots // dashboard snapshots
r.Post("/api/snapshots/", bind(m.CreateDashboardSnapshotCommand{}), CreateDashboardSnapshot) r.Post("/api/snapshots/", bind(m.CreateDashboardSnapshotCommand{}), CreateDashboardSnapshot)
r.Get("/dashboard/snapshot/*", Index) r.Get("/dashboard/snapshot/*", Index)
......
...@@ -27,3 +27,7 @@ type AdminUserListItem struct { ...@@ -27,3 +27,7 @@ type AdminUserListItem struct {
Login string `json:"login"` Login string `json:"login"`
IsGrafanaAdmin bool `json:"isGrafanaAdmin"` IsGrafanaAdmin bool `json:"isGrafanaAdmin"`
} }
type SendResetPasswordEmailForm struct {
UserOrEmail string `json:"userOrEmail" binding:"Required"`
}
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"
)
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 ViewResetPasswordForm(c *middleware.Context) Response {
return ApiSuccess("Email sent")
}
...@@ -5,7 +5,6 @@ type SendEmailCommand struct { ...@@ -5,7 +5,6 @@ type SendEmailCommand struct {
From string From string
Subject string Subject string
Body string Body string
Type string
Massive bool Massive bool
Info string Info string
} }
...@@ -16,13 +15,7 @@ type SendResetPasswordEmailCommand struct { ...@@ -16,13 +15,7 @@ type SendResetPasswordEmailCommand struct {
// create mail content // create mail content
func (m *SendEmailCommand) Content() string { func (m *SendEmailCommand) Content() string {
// set mail type contentType := "text/html; charset=UTF-8"
contentType := "text/plain; charset=UTF-8"
if m.Type == "html" {
contentType = "text/html; charset=UTF-8"
}
// create mail content
content := "From: " + m.From + "\r\nSubject: " + m.Subject + "\r\nContent-Type: " + contentType + "\r\n\r\n" + m.Body content := "From: " + m.From + "\r\nSubject: " + m.Subject + "\r\nContent-Type: " + contentType + "\r\n\r\n" + m.Body
return content return content
} }
...@@ -34,6 +27,5 @@ func NewSendEmailCommand(To []string, From, Subject, Body string) SendEmailComma ...@@ -34,6 +27,5 @@ func NewSendEmailCommand(To []string, From, Subject, Body string) SendEmailComma
From: From, From: From,
Subject: Subject, Subject: Subject,
Body: Body, Body: Body,
Type: "html",
} }
} }
...@@ -30,6 +30,16 @@ type User struct { ...@@ -30,6 +30,16 @@ type User struct {
Updated time.Time 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 // COMMANDS
......
...@@ -55,12 +55,6 @@ func processMailQueue() { ...@@ -55,12 +55,6 @@ func processMailQueue() {
} }
} }
func encodeRFC2047(text string) string {
// use mail's rfc2047 to encode any string
addr := mail.Address{Address: text}
return strings.Trim(addr.String(), " <>")
}
func handleEmailCommand(cmd *m.SendEmailCommand) error { func handleEmailCommand(cmd *m.SendEmailCommand) error {
log.Info("Sending on queue") log.Info("Sending on queue")
mailQueue <- cmd mailQueue <- cmd
...@@ -166,47 +160,6 @@ func sendToSmtpServer(recipients []string, msgContent []byte) error { ...@@ -166,47 +160,6 @@ func sendToSmtpServer(recipients []string, msgContent []byte) error {
} }
return client.Quit() return client.Quit()
// smtpServer := "smtp.gmail.com"
// auth := smtp.PlainAuth(
// "",
// "torkel.odegaard@gmail.com",
// "peslpwstnnloiksq",
// smtpServer,
// )
//
// from := mail.Address{Name: "test", Address: "torkel@test.com"}
// to := mail.Address{Name: "Torkel Ödegaard", Address: "torkel@raintank.io"}
// title := "Message from Grafana"
//
// body := "Testing email sending"
//
// header := make(map[string]string)
// header["From"] = from.String()
// header["To"] = to.String()
// header["Subject"] = encodeRFC2047(title)
// header["MIME-Version"] = "1.0"
// header["Content-Type"] = "text/plain; charset=\"utf-8\""
// header["Content-Transfer-Encoding"] = "base64"
//
// message := ""
// for k, v := range header {
// message += fmt.Sprintf("%s: %s\r\n", k, v)
// }
// message += "\r\n" + base64.StdEncoding.EncodeToString([]byte(body))
//
// // Connect to the server, authenticate, set the sender and recipient,
// // and send the email all in one step.
// err := smtp.SendMail(
// smtpServer+":587",
// auth,
// from.Address,
// []string{to.Address},
// []byte(message),
// )
// if err != nil {
// log.Info("Failed to send email: %v", err)
// }
// kkkk
} }
func buildAndSend(msg *m.SendEmailCommand) (int, error) { func buildAndSend(msg *m.SendEmailCommand) (int, error) {
......
...@@ -20,10 +20,10 @@ func getMailTmplData(u *m.User) map[interface{}]interface{} { ...@@ -20,10 +20,10 @@ func getMailTmplData(u *m.User) map[interface{}]interface{} {
data["AppUrl"] = setting.AppUrl data["AppUrl"] = setting.AppUrl
data["BuildVersion"] = setting.BuildVersion data["BuildVersion"] = setting.BuildVersion
data["BuildStamp"] = setting.BuildStamp data["BuildStamp"] = setting.BuildStamp
data["BuildCommit"] = setting.BuildCommit data["EmailCodeValidHours"] = setting.EmailCodeValidMinutes / 60
data["Subject"] = map[string]interface{}{} data["Subject"] = map[string]interface{}{}
if u != nil { if u != nil {
data["User"] = u data["Name"] = u.NameOrFallback()
} }
return data return data
} }
...@@ -35,6 +35,10 @@ func Init() error { ...@@ -35,6 +35,10 @@ func Init() error {
return errors.New("Invalid email address for smpt from_adress config") return errors.New("Invalid email address for smpt from_adress config")
} }
if setting.EmailCodeValidMinutes == 0 {
setting.EmailCodeValidMinutes = 120
}
return nil return nil
} }
...@@ -50,7 +54,7 @@ func subjectTemplateFunc(obj map[string]interface{}, value string) string { ...@@ -50,7 +54,7 @@ func subjectTemplateFunc(obj map[string]interface{}, value string) string {
func sendResetPasswordEmail(cmd *m.SendResetPasswordEmailCommand) error { func sendResetPasswordEmail(cmd *m.SendResetPasswordEmailCommand) error {
var buffer bytes.Buffer var buffer bytes.Buffer
var data = getMailTmplData(nil) var data = getMailTmplData(cmd.User)
code := CreateUserActiveCode(cmd.User, nil) code := CreateUserActiveCode(cmd.User, nil)
data["Code"] = code data["Code"] = code
...@@ -75,3 +79,35 @@ func CreateUserActiveCode(u *m.User, startInf interface{}) string { ...@@ -75,3 +79,35 @@ func CreateUserActiveCode(u *m.User, startInf interface{}) string {
code += hex.EncodeToString([]byte(u.Login)) code += hex.EncodeToString([]byte(u.Login))
return code return code
} }
// // verify active code when active account
// func VerifyUserActiveCode(code string) (user *User) {
// minutes := setting.Service.ActiveCodeLives
//
// if user = getVerifyUser(code); user != nil {
// // time limit code
// prefix := code[:base.TimeLimitCodeLength]
// data := com.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
//
// if base.VerifyTimeLimitCode(data, minutes, prefix) {
// return user
// }
// }
// return nil
// }
//
// // verify active code when active account
// func VerifyUserActiveCode(code string) (user *User) {
// minutes := setting.Service.ActiveCodeLives
//
// if user = getVerifyUser(code); user != nil {
// // time limit code
// prefix := code[:base.TimeLimitCodeLength]
// data := com.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
//
// if base.VerifyTimeLimitCode(data, minutes, prefix) {
// return user
// }
// }
// return nil
// }
...@@ -28,8 +28,8 @@ func TestNotifications(t *testing.T) { ...@@ -28,8 +28,8 @@ func TestNotifications(t *testing.T) {
Convey("When sending reset email password", func() { Convey("When sending reset email password", func() {
sendResetPasswordEmail(&m.SendResetPasswordEmailCommand{User: &m.User{Email: "asd@asd.com"}}) sendResetPasswordEmail(&m.SendResetPasswordEmailCommand{User: &m.User{Email: "asd@asd.com"}})
So(sentMail.Body, ShouldContainSubstring, "h2") So(sentMail.Body, ShouldContainSubstring, "body")
So(sentMail.Subject, ShouldEqual, "Welcome to Grafana") So(sentMail.Subject, ShouldEqual, "Reset your Grafana password")
So(sentMail.Body, ShouldNotContainSubstring, "Subject") So(sentMail.Body, ShouldNotContainSubstring, "Subject")
}) })
}) })
......
...@@ -21,13 +21,10 @@ function (angular, config) { ...@@ -21,13 +21,10 @@ function (angular, config) {
$scope.disableUserSignUp = config.disableUserSignUp; $scope.disableUserSignUp = config.disableUserSignUp;
$scope.loginMode = true; $scope.loginMode = true;
$scope.submitBtnClass = 'btn-inverse';
$scope.submitBtnText = 'Log in'; $scope.submitBtnText = 'Log in';
$scope.strengthClass = '';
$scope.init = function() { $scope.init = function() {
$scope.$watch("loginMode", $scope.loginModeChanged); $scope.$watch("loginMode", $scope.loginModeChanged);
$scope.passwordChanged();
var params = $location.search(); var params = $location.search();
if (params.failedMsg) { if (params.failedMsg) {
...@@ -56,27 +53,6 @@ function (angular, config) { ...@@ -56,27 +53,6 @@ function (angular, config) {
$scope.submitBtnText = newValue ? 'Log in' : 'Sign up'; $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() { $scope.signUp = function() {
if (!$scope.loginForm.$valid) { if (!$scope.loginForm.$valid) {
return; return;
......
define([ define([
'angular', 'angular',
'app',
'lodash'
], ],
function (angular, app, _) { function (angular) {
'use strict'; 'use strict';
var module = angular.module('grafana.controllers'); var module = angular.module('grafana.controllers');
module.controller('ResetPasswordCtrl', function($scope, contextSrv, backendSrv) { module.controller('ResetPasswordCtrl', function($scope, contextSrv, backendSrv, $location) {
contextSrv.sidemenu = false; contextSrv.sidemenu = false;
$scope.sendMode = true;
$scope.formModel = {}; $scope.formModel = {};
$scope.mode = 'send';
if ($location.search().code) {
$scope.mode = 'reset';
}
$scope.sendResetEmail = function() { $scope.sendResetEmail = function() {
if (!$scope.loginForm.$valid) { 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; return;
} }
backendSrv.post('/api/user/password/send-reset-email', $scope.formModel).then(function() { backendSrv.post('/api/user/password/send-reset-email', $scope.formModel).then(function() {
$location.path('login');
}); });
}; };
......
...@@ -18,4 +18,5 @@ define([ ...@@ -18,4 +18,5 @@ define([
'./topnav', './topnav',
'./giveFocus', './giveFocus',
'./annotationTooltip', './annotationTooltip',
'./passwordStrenght',
], function () {}); ], function () {});
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);
}
};
});
});
...@@ -42,7 +42,7 @@ ...@@ -42,7 +42,7 @@
<div class="tight-form" ng-if="!loginMode"> <div class="tight-form" ng-if="!loginMode">
<ul class="tight-form-list"> <ul class="tight-form-list">
<li class="tight-form-item" style="width: 80px"> <li class="tight-form-item" style="width: 79px">
<strong>Email</strong> <strong>Email</strong>
</li> </li>
<li> <li>
...@@ -54,24 +54,22 @@ ...@@ -54,24 +54,22 @@
<div class="tight-form" ng-if="!loginMode"> <div class="tight-form" ng-if="!loginMode">
<ul class="tight-form-list"> <ul class="tight-form-list">
<li class="tight-form-item" style="width: 80px"> <li class="tight-form-item" style="width: 79px">
<strong>Password</strong> <strong>Password</strong>
</li> </li>
<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> </li>
</ul> </ul>
<div class="clearfix"></div> <div class="clearfix"></div>
</div> </div>
<div class="password-strength small" ng-if="!loginMode" ng-class="strengthClass"> <div ng-if="!loginMode" style="margin-left: 97px; width: 254px;">
<em>{{strengthText}}</em> <password-strength password="formModel.password"></password-strength>
</div> </div>
<div class="login-submit-button-row"> <div class="login-submit-button-row">
<button type="submit" class="btn" ng-click="submit();" <button type="submit" class="btn" ng-click="submit();" ng-class="{'btn-inverse': !loginForm.$valid, 'btn-primary': loginForm.$valid}">
ng-class="{'btn-inverse': !loginForm.$valid, 'btn-primary': loginForm.$valid}">
{{submitBtnText}} {{submitBtnText}}
</button> </button>
</div> </div>
...@@ -93,7 +91,7 @@ ...@@ -93,7 +91,7 @@
<div class="row" style="margin-top: 40px"> <div class="row" style="margin-top: 40px">
<div class="text-center"> <div class="text-center">
<a href="reset-password/send"> <a href="user/password/send-reset-email">
Forgot your password? Forgot your password?
</a> </a>
</div> </div>
......
...@@ -3,7 +3,9 @@ ...@@ -3,7 +3,9 @@
<div class="login-box"> <div class="login-box">
<div class="login-box-logo"> <div class="login-box-logo">
<img src="img/logo_transparent_200x75.png"> <a href="login">
<img src="img/logo_transparent_200x75.png">
</a>
</div> </div>
<div class="login-inner-box"> <div class="login-inner-box">
...@@ -13,8 +15,8 @@ ...@@ -13,8 +15,8 @@
</button> </button>
</div> </div>
<form name="sendResetForm" class="login-form"> <form name="sendResetForm" class="login-form" ng-show="mode === 'send'">
<div class="tight-form" ng-if="sendMode"> <div class="tight-form last">
<ul class="tight-form-list"> <ul class="tight-form-list">
<li class="tight-form-item" style="width: 78px"> <li class="tight-form-item" style="width: 78px">
<strong>User</strong> <strong>User</strong>
...@@ -33,9 +35,56 @@ ...@@ -33,9 +35,56 @@
</div> </div>
</form> </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 class="clearfix"></div>
</div> </div>
<div class="row" style="margin-top: 40px">
<div class="text-center">
<a href="login">
Back to login
</a>
</div>
</div>
</div> </div>
</div> </div>
...@@ -97,7 +97,11 @@ define([ ...@@ -97,7 +97,11 @@ define([
templateUrl: 'app/partials/login.html', templateUrl: 'app/partials/login.html',
controller : 'LoginCtrl', controller : 'LoginCtrl',
}) })
.when('/reset-password/send', { .when('/user/password/send-reset-email', {
templateUrl: 'app/partials/reset_password.html',
controller : 'ResetPasswordCtrl',
})
.when('/user/password/reset', {
templateUrl: 'app/partials/reset_password.html', templateUrl: 'app/partials/reset_password.html',
controller : 'ResetPasswordCtrl', controller : 'ResetPasswordCtrl',
}) })
......
...@@ -50,19 +50,18 @@ ...@@ -50,19 +50,18 @@
.password-strength { .password-strength {
display: block; display: block;
width: 50px; width: 15%;
overflow: visible; overflow: visible;
white-space: nowrap; white-space: nowrap;
padding-top: 3px; padding-top: 3px;
margin-left: 97px;
color: darken(@textColor, 20%); color: darken(@textColor, 20%);
border-top: 3px solid @red; border-top: 3px solid @red;
&.password-strength-ok { &.password-strength-ok {
width: 170px; width: 40%;
border-top: 3px solid lighten(@yellow, 10%); border-top: 3px solid lighten(@yellow, 10%);
} }
&.password-strength-good { &.password-strength-good {
width: 254px; width: 100%;
border-top: 3px solid lighten(@green, 10%); border-top: 3px solid lighten(@green, 10%);
} }
} }
......
{{Subject .Subject "Welcome to Grafana"}} {{Subject .Subject "Reset your Grafana password"}}
<h2> <!DOCTYPE html>
{{.BuildVersion}} <html>
</h2> <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>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment