Vueify the login page

Signed-off-by: Christoph Wurst <christoph@winzerhof-wurst.at>
This commit is contained in:
Christoph Wurst 2019-05-21 08:58:35 +02:00
parent ccd8da66f2
commit 64c4bb5bce
No known key found for this signature in database
GPG key ID: CC42AC2A7F0E56D8
33 changed files with 745 additions and 9803 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -47,10 +47,12 @@ use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\Defaults;
use OCP\IConfig;
use OCP\IInitialStateService;
use OCP\ILogger;
use OCP\IRequest;
use OCP\ISession;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserManager;
use OCP\IUserSession;
use OCP\Util;
@ -78,6 +80,8 @@ class LoginController extends Controller {
private $throttler;
/** @var Chain */
private $loginChain;
/** @var IInitialStateService */
private $initialStateService;
public function __construct(?string $appName,
IRequest $request,
@ -89,7 +93,8 @@ class LoginController extends Controller {
ILogger $logger,
Defaults $defaults,
Throttler $throttler,
Chain $loginChain) {
Chain $loginChain,
IInitialStateService $initialStateService) {
parent::__construct($appName, $request);
$this->userManager = $userManager;
$this->config = $config;
@ -100,6 +105,7 @@ class LoginController extends Controller {
$this->defaults = $defaults;
$this->throttler = $throttler;
$this->loginChain = $loginChain;
$this->initialStateService = $initialStateService;
}
/**
@ -141,50 +147,37 @@ class LoginController extends Controller {
return new RedirectResponse(OC_Util::getDefaultPageUrl());
}
$parameters = array();
$loginMessages = $this->session->get('loginMessages');
$errors = [];
$messages = [];
if (is_array($loginMessages)) {
list($errors, $messages) = $loginMessages;
$this->initialStateService->provideInitialState('core', 'loginMessages', $messages);
$this->initialStateService->provideInitialState('core', 'loginErrors', $errors);
}
$this->session->remove('loginMessages');
foreach ($errors as $value) {
$parameters[$value] = true;
}
$parameters['messages'] = $messages;
if ($user !== null && $user !== '') {
$parameters['loginName'] = $user;
$parameters['user_autofocus'] = false;
$this->initialStateService->provideInitialState('core', 'loginUsername', $user);
} else {
$parameters['loginName'] = '';
$parameters['user_autofocus'] = true;
$this->initialStateService->provideInitialState('core', 'loginUsername', '');
}
$autocomplete = $this->config->getSystemValue('login_form_autocomplete', true);
if ($autocomplete){
$parameters['login_form_autocomplete'] = 'on';
} else {
$parameters['login_form_autocomplete'] = 'off';
}
$this->initialStateService->provideInitialState(
'core',
'loginAutocomplete',
$this->config->getSystemValue('login_form_autocomplete', true) === true
);
if (!empty($redirect_url)) {
$parameters['redirect_url'] = $redirect_url;
$this->initialStateService->provideInitialState('core', 'loginRedirectUrl', $redirect_url);
}
$parameters = $this->setPasswordResetParameters($user, $parameters);
$parameters['alt_login'] = OC_App::getAlternativeLogIns();
$this->initialStateService->provideInitialState(
'core',
'loginThrottleDelay',
$this->throttler->getDelay($this->request->getRemoteAddress())
);
if ($user !== null && $user !== '') {
$parameters['loginName'] = $user;
$parameters['user_autofocus'] = false;
} else {
$parameters['loginName'] = '';
$parameters['user_autofocus'] = true;
}
$parameters['throttle_delay'] = $this->throttler->getDelay($this->request->getRemoteAddress());
$this->setPasswordResetInitialState($user);
// OpenGraph Support: http://ogp.me/
Util::addHeader('meta', ['property' => 'og:title', 'content' => Util::sanitizeHTML($this->defaults->getName())]);
@ -194,45 +187,66 @@ class LoginController extends Controller {
Util::addHeader('meta', ['property' => 'og:type', 'content' => 'website']);
Util::addHeader('meta', ['property' => 'og:image', 'content' => $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-touch.png'))]);
$parameters = [
'alt_login' => OC_App::getAlternativeLogIns(),
];
return new TemplateResponse(
$this->appName, 'login', $parameters, 'guest'
);
}
/**
* Sets the password reset params.
* Sets the password reset state
*
* @param string $username
*/
private function setPasswordResetInitialState(?string $username): void {
if ($username !== null && $username !== '') {
$user = $this->userManager->get($username);
} else {
$user = null;
}
$passwordLink = $this->config->getSystemValue('lost_password_link', '');
$this->initialStateService->provideInitialState(
'core',
'loginResetPasswordLink',
$passwordLink
);
$this->initialStateService->provideInitialState(
'core',
'loginCanResetPassword',
$this->canResetPassword($passwordLink, $user)
);
}
/**
* @param string|null $passwordLink
* @param IUser|null $user
*
* Users may not change their passwords if:
* - The account is disabled
* - The backend doesn't support password resets
* - The password reset function is disabled
*
* @param string $user
* @param array $parameters
* @return array
* @return bool
*/
private function setPasswordResetParameters(?string $user,
array $parameters): array {
if ($user !== null && $user !== '') {
$userObj = $this->userManager->get($user);
} else {
$userObj = null;
private function canResetPassword(?string $passwordLink, ?IUser $user): bool {
if ($passwordLink === 'disabled') {
return false;
}
$parameters['resetPasswordLink'] = $this->config
->getSystemValue('lost_password_link', '');
if ($parameters['resetPasswordLink'] === 'disabled') {
$parameters['canResetPassword'] = false;
} else if (!$parameters['resetPasswordLink'] && $userObj !== null) {
$parameters['canResetPassword'] = $userObj->canChangePassword();
} else if ($userObj !== null && $userObj->isEnabled() === false) {
$parameters['canResetPassword'] = false;
} else {
$parameters['canResetPassword'] = true;
if (!$passwordLink && $user !== null) {
return $user->canChangePassword();
}
return $parameters;
if ($user !== null && $user->isEnabled() === false) {
return false;
}
return true;
}
private function generateRedirect(?string $redirectUrl): RedirectResponse {
@ -258,6 +272,7 @@ class LoginController extends Controller {
* @param string $redirect_url
* @param string $timezone
* @param string $timezone_offset
*
* @return RedirectResponse
*/
public function tryLogin(string $user,
@ -268,7 +283,7 @@ class LoginController extends Controller {
// If the user is already logged in and the CSRF check does not pass then
// simply redirect the user to the correct page as required. This is the
// case when an user has already logged-in, in another tab.
if(!$this->request->passesCSRFCheck()) {
if (!$this->request->passesCSRFCheck()) {
return $this->generateRedirect($redirect_url);
}
@ -303,6 +318,7 @@ class LoginController extends Controller {
* @param string $originalUser
* @param string $redirect_url
* @param string $loginMessage
*
* @return RedirectResponse
*/
private function createLoginFailedResponse(
@ -328,10 +344,11 @@ class LoginController extends Controller {
* @UseSession
* @BruteForceProtection(action=sudo)
*
* @param string $password
*
* @return DataResponse
* @license GNU AGPL version 3 or any later version
*
* @param string $password
* @return DataResponse
*/
public function confirmPassword($password) {
$loginName = $this->userSession->getLoginName();

View file

@ -151,7 +151,8 @@ form #datadirField legend {
absolutely positioned descendant icons */
}
#submit-wrapper .submit-icon {
#submit-wrapper .submit-icon,
#reset-password-wrapper .submit-icon {
position: absolute;
top: 22px;
right: 24px;
@ -174,10 +175,6 @@ form #datadirField legend {
text-overflow: ellipsis;
}
#reset-password-wrapper .submit-icon {
display: none;
}
#submit-wrapper .icon-loading-small {
position: absolute;
top: 22px;

BIN
core/js/dist/login.js vendored

Binary file not shown.

Binary file not shown.

BIN
core/js/dist/main.js vendored

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -27,14 +27,16 @@
export function loadState (app, key) {
const elem = document.querySelector(`#initial-state-${app}-${key}`);
if (elem === null) {
console.error('Could not find initial state of ' + app);
throw new Error('Could not find initial state of ' + app);
const msg = `Could not find initial state ${key} of ${app}`
console.debug(msg);
throw new Error(msg);
}
try {
return JSON.parse(atob(elem.value));
} catch (e) {
console.error('Could not parse initial state of ' + app);
throw new Error('Could not parse initial state of ' + app);
const msg = `Could not parse initial state ${key} of ${app}`
console.debug(msg);
throw new Error(msg);
}
}

View file

@ -1,14 +0,0 @@
import $ from 'jquery';
import jstz from 'jstimezonedetect';
$(document).ready(function () {
$('#timezone_offset').val((-new Date().getTimezoneOffset() / 60));
$('#timezone').val(jstz.determine().name());
// only enable the submit button once we are sure that the timezone is set
const $loginForm = $('form[name="login"]');
if ($loginForm.length) {
$loginForm.find('input#submit').prop('disabled', false);
}
}
);

View file

@ -0,0 +1,202 @@
<!--
- @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
-
- @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
-
- @license GNU AGPL version 3 or any later version
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as
- published by the Free Software Foundation, either version 3 of the
- License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<template>
<form method="post"
name="login"
@submit="submit">
<fieldset>
<div v-if="apacheAuthFailed"
class="warning">
{{ t('core', 'Server side authentication failed!') }}<br>
<small>{{ t('core', 'Please contact your administrator.') }}
</small>
</div>
<div v-for="message in messages"
class="warning">
{{ message }}<br>
</div>
<div v-if="internalException"
class="warning">
{{ t('core', 'An internal error occurred.') }}<br>
<small>{{ t('core', 'Please try again or contact your administrator.') }}
</small>
</div>
<div id="message"
class="hidden">
<img class="float-spinner" alt=""
:src="OC.imagePath('core', 'loading-dark.gif')">
<span id="messageText"></span>
<!-- the following div ensures that the spinner is always inside the #message div -->
<div style="clear: both;"></div>
</div>
<p class="grouptop"
:class="{shake: invalidPassword}">
<input type="text"
name="user"
id="user"
ref="user"
:autocomplete="autoCompleteAllowed ? 'on' : 'off'"
:placeholder="t('core', 'Username or email')"
:aria-label="t('core', 'Username or email')"
v-model="user"
@change="updateUsername"
required>
<label for="user" class="infield">{{ t('core', 'Username or email') }}</label>
</p>
<p class="groupbottom"
:class="{shake: invalidPassword}">
<input type="password"
name="password"
id="password"
ref="password"
:autocomplete="autoCompleteAllowed ? 'on' : 'off'"
:placeholder="t('core', 'Password')"
:aria-label="t('core', 'Password')"
required>
<label for="password"
class="infield">{{ t('Password') }}</label>
</p>
<div id="submit-wrapper">
<input type="submit"
id="submit"
class="login primary"
title=""
:value="!loading ? t('core', 'Log in') : t('core', 'Logging in …')" />
<div class="submit-icon"
:class="{
'icon-confirm-white': !loading,
'icon-loading-small': loading && invertedColors,
'icon-loading-small-dark': loading && !invertedColors,
}"></div>
</div>
<p v-if="invalidPassword"
class="warning wrongPasswordMsg">
{{ t('core', 'Wrong username or password.') }}
</p>
<p v-else-if="userDisabled"
class="warning userDisabledMsg">
{{ t('lib', 'User disabled') }}
</p>
<p v-if="throttleDelay && throttleDelay > 5000"
class="warning throttledMsg">
{{ t('core', 'We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds.') }}
</p>
<input v-if="redirectUrl"
type="hidden"
name="redirect_url"
:value="redirectUrl">
<input type="hidden"
name="timezone"
:value="timezone" />
<input type="hidden"
name="timezone_offset"
:value="timezoneOffset"/>
<input type="hidden"
name="requesttoken"
:value="OC.requestToken">
</fieldset>
</form>
</template>
<script>
import jstz from 'jstimezonedetect'
export default {
name: 'LoginForm',
props: {
username: {
type: String,
default: '',
},
redirectUrl: {
type: String,
},
errors: {
type: Array,
default: () => [],
},
messages: {
type: Array,
default: () => [],
},
throttleDelay: {
type: Number,
},
invertedColors: {
type: Boolean,
default: false,
},
autoCompleteAllowed: {
type: Boolean,
default: true,
},
},
data () {
return {
loading: false,
timezone: jstz.determine().name(),
timezoneOffset: (-new Date().getTimezoneOffset() / 60),
user: this.username,
password: '',
}
},
computed: {
apacheAuthFailed () {
return this.errors.indexOf('apacheAuthFailed') !== -1
},
internalException () {
return this.errors.indexOf('internalexception') !== -1
},
invalidPassword () {
return this.errors.indexOf('invalidpassword') !== -1
},
userDisabled () {
return this.errors.indexOf('userdisabled') !== -1
},
},
mounted () {
if (this.username === '') {
this.$refs.user.focus()
} else {
this.$refs.password.focus()
}
},
methods: {
updateUsername () {
this.$emit('update:username', this.user)
},
submit () {
this.loading = true
this.$emit('submit')
}
}
}
</script>
<style scoped>
</style>

View file

@ -0,0 +1,150 @@
<!--
- @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
-
- @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
-
- @license GNU AGPL version 3 or any later version
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as
- published by the Free Software Foundation, either version 3 of the
- License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<template>
<form @submit.prevent="submit">
<p>
<input type="text"
name="user"
id="user"
:placeholder="t('core', 'Username or email')"
:aria-label="t('core', 'Username or email')"
v-model="user"
@change="updateUsername"
required>
<!--<?php p($_['user_autofocus'] ? 'autofocus' : ''); ?>
autocomplete="<?php p($_['login_form_autocomplete']); ?>" autocapitalize="none" autocorrect="off"-->
<label for="user" class="infield">{{ t('core', 'Username or email') }}</label>
</p>
<div id="reset-password-wrapper">
<input type="submit"
id="reset-password-submit"
class="login primary"
title=""
:value="t('core', 'Reset password')"/>
<div class="submit-icon"
:class="{
'icon-confirm-white': !loading,
'icon-loading-small': loading && invertedColors,
'icon-loading-small-dark': loading && !invertedColors,
}"></div>
</div>
<p v-if="message === 'send-success'"
class="update">
{{ t('core', 'We have sent a password reset e-mail to the e-mail address known to us for this account. If you do not receive it within a reasonable amount of time, check your spam/junk folders.') }}
<br>
{{ t('core', 'If it is not there ask your local administrator.') }}
</p>
<p v-else-if="message === 'send-error'"
class="update warning">
{{ t('core', 'Couldn\'t send reset email. Please contact your administrator.') }}
</p>
<p v-else-if="message === 'reset-error'"
class="update warning">
{{ t('core', 'Password can not be changed. Please contact your administrator.') }}
</p>
<p v-else-if="message"
class="update"
:class="{warning: error}">
</p>
<a href="#"
@click.prevent="$emit('abort')">
{{ t('core', 'Back to login') }}
</a>
</form>
</template>
<script>
import Axios from 'nextcloud-axios'
import {generateUrl} from '../../OC/routing'
export default {
name: 'ResetPassword',
props: {
username: {
type: String,
required: true,
},
resetPasswordLink: {
type: String,
required: true,
},
invertedColors: {
type: Boolean,
default: false,
}
},
data() {
return {
error: false,
loading: false,
message: undefined,
user: this.username,
}
},
watch: {
username (value) {
this.user = value
}
},
methods: {
updateUsername () {
this.$emit('update:username', this.user)
},
submit () {
this.loading = true
this.error = false
this.message = ''
const url = generateUrl('/lostpassword/email');
const data = {
user: this.user,
}
return Axios.post(url, data)
.then(resp => resp.data)
.then(data => {
if (data.status !== 'success') {
throw new Error(`got status ${data.status}`)
}
this.message = 'send-success'
})
.catch(e => {
console.error('could not send reset e-mail request', e)
this.error = true
this.message = 'send-error'
})
.then(() => this.loading = false)
}
},
}
</script>
<style scoped>
.update {
width: auto;
}
</style>

View file

@ -1,48 +1,63 @@
/**
* Copyright (c) 2015
* Vincent Petry <pvince81@owncloud.com>
* Jan-Christoph Borchardt, http://jancborchardt.net
* This file is licensed under the Affero General Public License version 3 or later.
* See the COPYING-README file.
/*
* @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import $ from 'jquery'
import Vue from 'vue';
import queryString from 'query-string';
import './lostpassword'
import './Util/visitortimezone'
import OC from './OC/index'; // TODO: Not needed but L10n breaks if removed
import LoginView from './views/Login.vue';
import Nextcloud from './mixins/Nextcloud';
function onLogin () {
// Only if password reset form is not active
if ($('form[name=login][action]').length === 0) {
$('#submit-wrapper .submit-icon')
.removeClass('icon-confirm-white')
.addClass(OCA.Theming && OCA.Theming.inverted
? 'icon-loading-small'
: 'icon-loading-small-dark');
$('#submit')
.attr('value', t('core', 'Logging in …'));
$('.login-additional').fadeOut();
return true;
}
return false;
}
function rememberLogin () {
if ($(this).is(":checked")) {
if ($("#user").val() && $("#password").val()) {
$('#submit').trigger('click');
}
}
}
$(document).ready(function () {
$('form[name=login]').submit(onLogin);
$('#remember_login').click(rememberLogin);
const clearParamRegex = new RegExp('clear=1');
if (clearParamRegex.test(window.location.href)) {
const query = queryString.parse(location.search);
if (query.clear === '1') {
try {
window.localStorage.clear();
window.sessionStorage.clear();
console.debug('Browser storage cleared');
} catch (e) {
console.error('Could not clear browser storage', e);
}
});
}
Vue.mixin(Nextcloud);
const fromStateOr = (key, orValue) => {
try {
return OCP.InitialState.loadState('core', key)
} catch (e) {
return orValue
}
}
const View = Vue.extend(LoginView);
new View({
propsData: {
errors: fromStateOr('loginErrors', []),
messages: fromStateOr('loginMessages', []),
redirectUrl: fromStateOr('loginRedirectUrl', undefined),
username: fromStateOr('loginUsername', ''),
throttleDelay: fromStateOr('loginThrottleDelay', 0),
invertedColors: OCA.Theming && OCA.Theming.inverted,
canResetPassword: fromStateOr('loginCanResetPassword', false),
resetPasswordLink: fromStateOr('loginResetPasswordLink', ''),
autoCompleteAllowed: fromStateOr('loginAutocomplete', true),
}
}).$mount('#login');

View file

@ -1,195 +0,0 @@
import $ from 'jquery'
import OC from './OC/index'
const sendErrorMsg = t('core', 'Couldn\'t send reset email. Please contact your administrator.');
const sendSuccessMsg = t('core', 'We have send a password reset e-mail to the e-mail address known to us for this account. If you do not receive it within a reasonable amount of time, check your spam/junk folders.<br>If it is not there ask your local administrator.');
const encryptedMsg = t('core', "Your files are encrypted. There will be no way to get your data back after your password is reset.<br />If you are not sure what to do, please contact your administrator before you continue. <br />Do you really want to continue?")
+ ('<br /><input type="checkbox" id="encrypted-continue" class="checkbox checkbox--white" value="Yes" />')
+ '<label for="encrypted-continue">'
+ t('core', 'I know what I\'m doing')
+ '</label><br />';
const resetErrorMsg = t('core', 'Password can not be changed. Please contact your administrator.');
function init () {
$('#lost-password[href=""]').click(resetLink);
$('#lost-password-back').click(backToLogin);
$('form[name=login]').submit(onSendLink);
$('#reset-password #submit').click(resetPassword);
resetButtons();
}
function resetButtons () {
$('#reset-password-wrapper .submit-icon')
.addClass('icon-confirm-white')
.removeClass('icon-loading-small-dark');
$('#reset-password-submit')
.attr('value', t('core', 'Reset password'))
.prop('disabled', false);
$('#user').prop('disabled', false);
$('.login-additional').fadeIn();
}
function backToLogin (event) {
event.preventDefault();
$('#reset-password-wrapper').slideUp().fadeOut();
$('#lost-password').slideDown().fadeIn();
$('#lost-password-back').hide();
$('.remember-login-container').slideDown().fadeIn();
$('#submit-wrapper').slideDown().fadeIn();
$('.groupbottom').slideDown().fadeIn();
$('#user').parent().addClass('grouptop');
$('#password').attr('required', true);
$('form[name=login]').removeAttr('action');
$('#user').focus();
}
function resetLink (event) {
event.preventDefault();
$('#lost-password').hide();
$('.wrongPasswordMsg').hide();
$('#lost-password-back').slideDown().fadeIn();
$('.remember-login-container').slideUp().fadeOut();
$('#submit-wrapper').slideUp().fadeOut();
$('.groupbottom').slideUp().fadeOut(function () {
$('#user').parent().removeClass('grouptop');
});
$('#reset-password-wrapper').slideDown().fadeIn();
$('#password').attr('required', false);
$('form[name=login]').attr('action', 'lostpassword/email');
$('#user').focus();
// Generate a browser warning for required fields if field empty
if ($('#user').val().length === 0) {
$('#submit').trigger('click');
} else {
if (OC.config.lost_password_link === 'disabled') {
return;
} else if (OC.config.lost_password_link) {
window.location = OC.config.lost_password_link;
} else {
onSendLink();
}
}
}
function onSendLink (event) {
// Only if password reset form is active
if ($('form[name=login][action]').length === 1) {
if (event) {
event.preventDefault();
}
$('#reset-password-wrapper .submit-icon')
.removeClass('icon-confirm-white')
.addClass('icon-loading-small-dark');
$('#reset-password-submit')
.attr('value', t('core', 'Sending email …'))
.prop('disabled', true);
$('#user').prop('disabled', true);
$('.login-additional').fadeOut();
$.post(
OC.generateUrl('/lostpassword/email'),
{
user: $('#user').val()
},
sendLinkDone
).fail(function () {
sendLinkError(sendErrorMsg);
});
}
}
function sendLinkDone (result) {
var sendErrorMsg;
if (result && result.status === 'success') {
sendLinkSuccess();
} else {
if (result && result.msg) {
sendErrorMsg = result.msg;
} else {
sendErrorMsg = sendErrorMsg;
}
sendLinkError(sendErrorMsg);
}
}
function sendLinkSuccess (msg) {
const node = getSendStatusNode();
// update is the better success message styling
node.addClass('update').css({width: 'auto'});
node.html(sendSuccessMsg);
resetButtons();
}
function sendLinkError (msg) {
const node = getSendStatusNode();
node.addClass('warning');
node.html(msg);
resetButtons();
}
function getSendStatusNode () {
if (!$('#lost-password').length) {
$('<p id="lost-password"></p>').insertBefore($('#remember_login'));
} else {
$('#lost-password').replaceWith($('<p id="lost-password"></p>'));
}
return $('#lost-password');
}
function resetPassword (event) {
event.preventDefault();
if ($('#password').val()) {
$.post(
$('#password').parents('form').attr('action'),
{
password: $('#password').val(),
proceed: $('#encrypted-continue').is(':checked') ? 'true' : 'false'
},
resetDone
);
}
if ($('#encrypted-continue').is(':checked')) {
$('#reset-password #submit').hide();
$('#reset-password #float-spinner').removeClass('hidden');
}
}
function resetDone (result) {
if (result && result.status === 'success') {
redirect('/login?user=' + result.user);
} else {
if (result && result.msg) {
resetError(result.msg);
} else if (result && result.encryption) {
resetError(encryptedMsg);
} else {
resetError(resetErrorMsg);
}
resetError(resetErrorMsg);
}
}
function redirect (url) {
window.location = OC.generateUrl(url);
}
function resetError (msg) {
var node = getResetStatusNode();
node.addClass('warning');
node.html(msg);
}
function getResetStatusNode () {
if (!$('#lost-password').length) {
$('<p id="lost-password"></p>').insertBefore($('#reset-password fieldset'));
} else {
$('#lost-password').replaceWith($('<p id="lost-password"></p>'));
}
return $('#lost-password');
}
$(document).ready(init);

View file

@ -0,0 +1,35 @@
/*
* @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import L10n from '../OC/l10n'
import OC from '../OC/index'
export default {
data() {
return {
OC,
}
},
methods: {
t: L10n.translate.bind(L10n),
n: L10n.translatePlural.bind(L10n),
},
}

125
core/src/views/Login.vue Normal file
View file

@ -0,0 +1,125 @@
<!--
- @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
-
- @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
-
- @license GNU AGPL version 3 or any later version
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as
- published by the Free Software Foundation, either version 3 of the
- License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<template>
<div>
<transition name="fade" mode="out-in">
<div v-if="!resetPassword"
key="login">
<LoginForm
:username.sync="user"
:redirect-url="redirectUrl"
:messages="messages"
:errors="errors"
:throttle-delay="throttleDelay"
:inverted-colors="invertedColors"
:auto-complete-allowed="autoCompleteAllowed"
@submit="loading = true"/>
<a v-if="canResetPassword && resetPasswordLink !== ''"
id="lost-password"
:href="resetPasswordLink">
{{ t('core', 'Forgot password?') }}
</a>
<a v-else-if="canResetPassword && !resetPassword"
id="lost-password"
:href="resetPasswordLink"
@click.prevent="resetPassword = true">
{{ t('core', 'Forgot password?') }}
</a>
</div>
<div v-else-if="!loading && canResetPassword"
key="reset"
class="login-additional">
<div class="lost-password-container">
<ResetPassword v-if="resetPassword"
:username.sync="user"
:reset-password-link="resetPasswordLink"
:inverted-colors="invertedColors"
@abort="resetPassword = false"/>
</div>
</div>
</transition>
</div>
</template>
<script>
import LoginForm from '../components/login/LoginForm.vue'
import ResetPassword from '../components/login/ResetPassword.vue'
export default {
name: 'Login',
props: {
username: {
type: String,
default: '',
},
redirectUrl: {
type: String,
},
errors: {
type: Array,
default: () => [],
},
messages: {
type: Array,
default: () => [],
},
throttleDelay: {
type: Number,
},
canResetPassword: {
type: Boolean,
default: false,
},
resetPasswordLink: {
type: String,
},
invertedColors: {
type: Boolean,
default: false,
},
autoCompleteAllowed: {
type: Boolean,
default: true,
},
},
components: {
LoginForm,
ResetPassword,
},
data () {
return {
loading: false,
user: this.username,
resetPassword: false,
}
}
}
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity .3s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
opacity: 0;
}
</style>

View file

@ -1,105 +1,9 @@
<?php /** @var $l \OCP\IL10N */ ?>
<?php
script('core', 'dist/login');
use OC\Core\Controller\LoginController;
?>
<!--[if IE 8]><style>input[type="checkbox"]{padding:0;}</style><![endif]-->
<form method="post" name="login">
<fieldset>
<?php if (!empty($_['redirect_url'])) {
print_unescaped('<input type="hidden" name="redirect_url" value="' . \OCP\Util::sanitizeHTML($_['redirect_url']) . '">');
} ?>
<?php if (isset($_['apacheauthfailed']) && $_['apacheauthfailed']): ?>
<div class="warning">
<?php p($l->t('Server side authentication failed!')); ?><br>
<small><?php p($l->t('Please contact your administrator.')); ?></small>
</div>
<?php endif; ?>
<?php foreach($_['messages'] as $message): ?>
<div class="warning">
<?php p($message); ?><br>
</div>
<?php endforeach; ?>
<?php if (isset($_['internalexception']) && $_['internalexception']): ?>
<div class="warning">
<?php p($l->t('An internal error occurred.')); ?><br>
<small><?php p($l->t('Please try again or contact your administrator.')); ?></small>
</div>
<?php endif; ?>
<div id="message" class="hidden">
<img class="float-spinner" alt=""
src="<?php p(image_path('core', 'loading-dark.gif'));?>">
<span id="messageText"></span>
<!-- the following div ensures that the spinner is always inside the #message div -->
<div style="clear: both;"></div>
</div>
<p class="grouptop<?php if (!empty($_[LoginController::LOGIN_MSG_INVALIDPASSWORD])) { ?> shake<?php } ?>">
<input type="text" name="user" id="user"
placeholder="<?php p($l->t('Username or email')); ?>"
aria-label="<?php p($l->t('Username or email')); ?>"
value="<?php p($_['loginName']); ?>"
<?php p($_['user_autofocus'] ? 'autofocus' : ''); ?>
autocomplete="<?php p($_['login_form_autocomplete']); ?>" autocapitalize="none" autocorrect="off" required>
<label for="user" class="infield"><?php p($l->t('Username or email')); ?></label>
</p>
<p class="groupbottom<?php if (!empty($_[LoginController::LOGIN_MSG_INVALIDPASSWORD])) { ?> shake<?php } ?>">
<input type="password" name="password" id="password" value=""
placeholder="<?php p($l->t('Password')); ?>"
aria-label="<?php p($l->t('Password')); ?>"
<?php p($_['user_autofocus'] ? '' : 'autofocus'); ?>
autocomplete="<?php p($_['login_form_autocomplete']); ?>" autocapitalize="none" autocorrect="off" required>
<label for="password" class="infield"><?php p($l->t('Password')); ?></label>
</p>
<div id="submit-wrapper">
<input type="submit" id="submit" class="login primary" title="" value="<?php p($l->t('Log in')); ?>" disabled="disabled" />
<div class="submit-icon icon-confirm-white"></div>
</div>
<?php if (!empty($_[LoginController::LOGIN_MSG_INVALIDPASSWORD])) { ?>
<p class="warning wrongPasswordMsg">
<?php p($l->t('Wrong username or password.')); ?>
</p>
<?php } else if (!empty($_[LoginController::LOGIN_MSG_USERDISABLED])) { ?>
<p class="warning userDisabledMsg">
<?php p(\OC::$server->getL10N('lib')->t('User disabled')); ?>
</p>
<?php } ?>
<?php if ($_['throttle_delay'] > 5000) { ?>
<p class="warning throttledMsg">
<?php p($l->t('We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds.')); ?>
</p>
<?php } ?>
<?php if (!empty($_['canResetPassword'])) { ?>
<div id="reset-password-wrapper" style="display: none;">
<input type="submit" id="reset-password-submit" class="login primary" title="" value="<?php p($l->t('Reset password')); ?>" disabled="disabled" />
<div class="submit-icon icon-confirm-white"></div>
</div>
<?php } ?>
<div class="login-additional">
<?php if (!empty($_['canResetPassword'])) { ?>
<div class="lost-password-container">
<a id="lost-password" href="<?php p($_['resetPasswordLink']); ?>">
<?php p($l->t('Forgot password?')); ?>
</a>
<a id="lost-password-back" href="" style="display:none;">
<?php p($l->t('Back to login')); ?>
</a>
</div>
<?php } ?>
</div>
<input type="hidden" name="timezone_offset" id="timezone_offset"/>
<input type="hidden" name="timezone" id="timezone"/>
<input type="hidden" name="requesttoken" value="<?php p($_['requesttoken']) ?>">
</fieldset>
</form>
<div id="login"></div>
<?php if (!empty($_['alt_login'])) { ?>
<form id="alternative-logins">
<fieldset>

View file

@ -1,5 +1,6 @@
const path = require('path');
const webpack = require('webpack');
const { VueLoaderPlugin } = require('vue-loader');
module.exports = [
{
@ -16,11 +17,11 @@ module.exports = [
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
use: ['vue-style-loader', 'style-loader', 'css-loader']
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader']
use: ['vue-style-loader', 'style-loader', 'css-loader', 'sass-loader']
},
{
test: /davclient/,
@ -31,6 +32,10 @@ module.exports = [
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.(png|jpg|gif)$/,
loader: 'url-loader',
@ -53,7 +58,8 @@ module.exports = [
'_': "underscore",
$: "jquery",
jQuery: "jquery"
})
}),
new VueLoaderPlugin(),
],
resolve: {
alias: {

21
package-lock.json generated
View file

@ -2372,8 +2372,7 @@
"decode-uri-component": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz",
"integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=",
"dev": true
"integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU="
},
"define-property": {
"version": "2.0.2",
@ -5098,8 +5097,7 @@
"object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=",
"dev": true
"integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM="
},
"object-copy": {
"version": "0.1.0",
@ -5775,6 +5773,16 @@
"resolved": "https://registry.npmjs.org/qs/-/qs-2.3.3.tgz",
"integrity": "sha1-6eha2+ddoLvkyOBHaghikPhjtAQ="
},
"query-string": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/query-string/-/query-string-5.1.1.tgz",
"integrity": "sha512-gjWOsm2SoGlgLEdAGt7a6slVOk9mGiXmPFMqrEhLQ68rhQuBnpfs3+EmlvqKyxnCo9/PPlF+9MtY02S1aFg+Jw==",
"requires": {
"decode-uri-component": "^0.2.0",
"object-assign": "^4.1.0",
"strict-uri-encode": "^1.0.0"
}
},
"querystring": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz",
@ -6612,6 +6620,11 @@
"version": "git+https://github.com/MorrisJobke/strengthify.git#99ff58bdc29fabfd0b1073662b16432d515a6516",
"from": "git+https://github.com/MorrisJobke/strengthify.git#0.5.8"
},
"strict-uri-encode": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/strict-uri-encode/-/strict-uri-encode-1.1.0.tgz",
"integrity": "sha1-J5siXfHVgrH1TmWt3UNS4Y+qBxM="
},
"string-width": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz",

View file

@ -45,6 +45,7 @@
"nextcloud-password-confirmation": "^0.4.1",
"nextcloud-vue": "^0.11.3",
"nextcloud-vue-collections": "^0.5.2",
"query-string": "^5.1.1",
"snap.js": "^2.0.9",
"strengthify": "git+https://github.com/MorrisJobke/strengthify.git#0.5.8",
"underscore": "^1.9.1",

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -24,18 +24,15 @@ namespace Tests\Core\Controller;
use OC\Authentication\Login\Chain as LoginChain;
use OC\Authentication\Login\LoginData;
use OC\Authentication\Login\LoginResult;
use OC\Authentication\Token\IToken;
use OC\Authentication\TwoFactorAuth\Manager;
use OC\Authentication\TwoFactorAuth\ProviderSet;
use OC\Core\Controller\LoginController;
use OC\Security\Bruteforce\Throttler;
use OC\User\Session;
use OCA\TwoFactorBackupCodes\Provider\BackupCodesProvider;
use OCP\AppFramework\Http\RedirectResponse;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\Authentication\TwoFactorAuth\IProvider;
use OCP\Defaults;
use OCP\IConfig;
use OCP\IInitialStateService;
use OCP\ILogger;
use OCP\IRequest;
use OCP\ISession;
@ -83,6 +80,9 @@ class LoginControllerTest extends TestCase {
/** @var LoginChain|MockObject */
private $chain;
/** @var IInitialStateService|MockObject */
private $initialStateService;
public function setUp() {
parent::setUp();
$this->request = $this->createMock(IRequest::class);
@ -96,6 +96,7 @@ class LoginControllerTest extends TestCase {
$this->defaults = $this->createMock(Defaults::class);
$this->throttler = $this->createMock(Throttler::class);
$this->chain = $this->createMock(LoginChain::class);
$this->initialStateService = $this->createMock(IInitialStateService::class);
$this->request->method('getRemoteAddress')
->willReturn('1.2.3.4');
@ -116,7 +117,8 @@ class LoginControllerTest extends TestCase {
$this->logger,
$this->defaults,
$this->throttler,
$this->chain
$this->chain,
$this->initialStateService
);
}
@ -201,24 +203,32 @@ class LoginControllerTest extends TestCase {
],
]
);
$this->initialStateService->expects($this->at(0))
->method('provideInitialState')
->with(
'core',
'loginMessages',
[
'MessageArray1',
'MessageArray2',
]
);
$this->initialStateService->expects($this->at(1))
->method('provideInitialState')
->with(
'core',
'loginErrors',
[
'ErrorArray1',
'ErrorArray2',
]
);
$expectedResponse = new TemplateResponse(
'core',
'login',
[
'ErrorArray1' => true,
'ErrorArray2' => true,
'messages' => [
'MessageArray1',
'MessageArray2',
],
'loginName' => '',
'user_autofocus' => true,
'canResetPassword' => true,
'alt_login' => [],
'resetPasswordLink' => null,
'throttle_delay' => 1000,
'login_form_autocomplete' => 'off',
],
'guest'
);
@ -230,20 +240,19 @@ class LoginControllerTest extends TestCase {
->expects($this->once())
->method('isLoggedIn')
->willReturn(false);
$this->initialStateService->expects($this->at(2))
->method('provideInitialState')
->with(
'core',
'loginRedirectUrl',
'login/flow'
);
$expectedResponse = new TemplateResponse(
'core',
'login',
[
'messages' => [],
'redirect_url' => 'login/flow',
'loginName' => '',
'user_autofocus' => true,
'canResetPassword' => true,
'alt_login' => [],
'resetPasswordLink' => null,
'throttle_delay' => 1000,
'login_form_autocomplete' => 'off',
],
'guest'
);
@ -292,19 +301,26 @@ class LoginControllerTest extends TestCase {
->method('get')
->with('LdapUser')
->willReturn($user);
$this->initialStateService->expects($this->at(0))
->method('provideInitialState')
->with(
'core',
'loginUsername',
'LdapUser'
);
$this->initialStateService->expects($this->at(4))
->method('provideInitialState')
->with(
'core',
'loginCanResetPassword',
$expectedResult
);
$expectedResponse = new TemplateResponse(
'core',
'login',
[
'messages' => [],
'loginName' => 'LdapUser',
'user_autofocus' => false,
'canResetPassword' => $expectedResult,
'alt_login' => [],
'resetPasswordLink' => false,
'throttle_delay' => 1000,
'login_form_autocomplete' => 'on',
],
'guest'
);
@ -332,19 +348,33 @@ class LoginControllerTest extends TestCase {
->method('get')
->with('0')
->willReturn($user);
$this->initialStateService->expects($this->at(1))
->method('provideInitialState')
->with(
'core',
'loginAutocomplete',
true
);
$this->initialStateService->expects($this->at(3))
->method('provideInitialState')
->with(
'core',
'loginResetPasswordLink',
false
);
$this->initialStateService->expects($this->at(4))
->method('provideInitialState')
->with(
'core',
'loginCanResetPassword',
false
);
$expectedResponse = new TemplateResponse(
'core',
'login',
[
'messages' => [],
'loginName' => '0',
'user_autofocus' => false,
'canResetPassword' => false,
'alt_login' => [],
'resetPasswordLink' => false,
'throttle_delay' => 1000,
'login_form_autocomplete' => 'on',
],
'guest'
);