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) {
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", wrap(ViewResetPasswordForm))
// dashboard snapshots
r.Post("/api/snapshots/", bind(m.CreateDashboardSnapshotCommand{}), CreateDashboardSnapshot)
r.Get("/dashboard/snapshot/*", Index)
......
......@@ -27,3 +27,7 @@ type AdminUserListItem struct {
Login string `json:"login"`
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 {
From string
Subject string
Body string
Type string
Massive bool
Info string
}
......@@ -16,13 +15,7 @@ type SendResetPasswordEmailCommand struct {
// create mail content
func (m *SendEmailCommand) Content() string {
// set mail type
contentType := "text/plain; charset=UTF-8"
if m.Type == "html" {
contentType = "text/html; charset=UTF-8"
}
// create mail content
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
}
......@@ -34,6 +27,5 @@ func NewSendEmailCommand(To []string, From, Subject, Body string) SendEmailComma
From: From,
Subject: Subject,
Body: Body,
Type: "html",
}
}
......@@ -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
......
......@@ -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 {
log.Info("Sending on queue")
mailQueue <- cmd
......@@ -166,47 +160,6 @@ func sendToSmtpServer(recipients []string, msgContent []byte) error {
}
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) {
......
......@@ -20,10 +20,10 @@ func getMailTmplData(u *m.User) map[interface{}]interface{} {
data["AppUrl"] = setting.AppUrl
data["BuildVersion"] = setting.BuildVersion
data["BuildStamp"] = setting.BuildStamp
data["BuildCommit"] = setting.BuildCommit
data["EmailCodeValidHours"] = setting.EmailCodeValidMinutes / 60
data["Subject"] = map[string]interface{}{}
if u != nil {
data["User"] = u
data["Name"] = u.NameOrFallback()
}
return data
}
......@@ -35,6 +35,10 @@ func Init() error {
return errors.New("Invalid email address for smpt from_adress config")
}
if setting.EmailCodeValidMinutes == 0 {
setting.EmailCodeValidMinutes = 120
}
return nil
}
......@@ -50,7 +54,7 @@ func subjectTemplateFunc(obj map[string]interface{}, value string) string {
func sendResetPasswordEmail(cmd *m.SendResetPasswordEmailCommand) error {
var buffer bytes.Buffer
var data = getMailTmplData(nil)
var data = getMailTmplData(cmd.User)
code := CreateUserActiveCode(cmd.User, nil)
data["Code"] = code
......@@ -75,3 +79,35 @@ func CreateUserActiveCode(u *m.User, startInf interface{}) string {
code += hex.EncodeToString([]byte(u.Login))
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) {
Convey("When sending reset email password", func() {
sendResetPasswordEmail(&m.SendResetPasswordEmailCommand{User: &m.User{Email: "asd@asd.com"}})
So(sentMail.Body, ShouldContainSubstring, "h2")
So(sentMail.Subject, ShouldEqual, "Welcome to Grafana")
So(sentMail.Body, ShouldContainSubstring, "body")
So(sentMail.Subject, ShouldEqual, "Reset your Grafana password")
So(sentMail.Body, ShouldNotContainSubstring, "Subject")
})
})
......
......@@ -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;
......
define([
'angular',
'app',
'lodash'
],
function (angular, app, _) {
function (angular) {
'use strict';
var module = angular.module('grafana.controllers');
module.controller('ResetPasswordCtrl', function($scope, contextSrv, backendSrv) {
module.controller('ResetPasswordCtrl', function($scope, contextSrv, backendSrv, $location) {
contextSrv.sidemenu = false;
$scope.sendMode = true;
$scope.formModel = {};
$scope.mode = 'send';
if ($location.search().code) {
$scope.mode = 'reset';
}
$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;
}
backendSrv.post('/api/user/password/send-reset-email', $scope.formModel).then(function() {
$location.path('login');
});
};
......
......@@ -18,4 +18,5 @@ define([
'./topnav',
'./giveFocus',
'./annotationTooltip',
'./passwordStrenght',
], 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 @@
<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>
......@@ -93,7 +91,7 @@
<div class="row" style="margin-top: 40px">
<div class="text-center">
<a href="reset-password/send">
<a href="user/password/send-reset-email">
Forgot your password?
</a>
</div>
......
......@@ -3,7 +3,9 @@
<div class="login-box">
<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 class="login-inner-box">
......@@ -13,8 +15,8 @@
</button>
</div>
<form name="sendResetForm" class="login-form">
<div class="tight-form" ng-if="sendMode">
<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>
......@@ -33,9 +35,56 @@
</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>
......@@ -97,7 +97,11 @@ define([
templateUrl: 'app/partials/login.html',
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',
controller : 'ResetPasswordCtrl',
})
......
......@@ -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%);
}
}
......
{{Subject .Subject "Welcome to Grafana"}}
{{Subject .Subject "Reset your Grafana password"}}
<h2>
{{.BuildVersion}}
</h2>
<!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>
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