Skip to content

Instantly share code, notes, and snippets.

@bodia-uz
Created March 12, 2018 20:24
Show Gist options
  • Save bodia-uz/9b9c2aaca7b82160d72da25b6e458591 to your computer and use it in GitHub Desktop.
Save bodia-uz/9b9c2aaca7b82160d72da25b6e458591 to your computer and use it in GitHub Desktop.
import {
isAbsoluteURL,
isTrustedURL,
appendParamsToURL,
redirectToURL
} from '../url-fns';
class LoginController {
/*@ngInject*/
constructor($rootScope, $log, $state, commonAuthUser) {
this.$rootScope = $rootScope;
this.$log = $log;
this.$state = $state;
this.commonAuthUser = commonAuthUser;
this.user = {
login: '',
password: ''
};
this.isPasswordVisible = false;
}
redirectToAccount() {
const { accountAppUrl } = this.commonAuthUser.config;
const token = this.commonAuthUser.getToken();
redirectToURL(`${accountAppUrl}/#/auth/check?token=${token}`);
}
redirectToTarget(){
const { callback: callbackURL } = this.$state.params;
if (callbackURL) {
if (!isAbsoluteURL(callbackURL)) {
redirectToURL(callbackURL);
return;
}
if (isTrustedURL(callbackURL)) {
redirectToURL(appendParamsToURL(callbackURL, {token: this.commonAuthUser.getToken()}));
return;
}
}
this.$state.go(this.commonAuthUser.getTargetState(), {}, { location: 'replace' });
}
submit(form) {
if (form.$valid && !this.isLoading) {
this.isLoading = true;
this.error = null;
this.commonAuthUser
.login(this.user.login, this.user.password)
.then(data => {
this.$log.log('Logged in:', data);
if (data.status === 'New') {
// NOTE: redirect to account app, to allow fill in user account data
this.redirectToAccount();
}
this.redirectToTarget();
})
.catch(response => {
const { status, data } = response;
this.error = (
status === 400 || status === 401 || status === 403 ?
'Неправильный логин или пароль' :
'Произошла ошибка. Пожалуйста, попробуйте позже.'
);
this.$log.warn('Login error:', data);
})
.finally(() => {
this.isLoading = false;
});
}
}
}
export default {
template: require('./auth-login.html'),
controller: LoginController,
controllerAs: 'vm'
};
<header class="auth__header">
Вход
</header>
<div class="auth__content">
<form name="loginForm" ng-submit="vm.submit(loginForm)" novalidate>
<div class="auth__form-group">
<label class="auth__control-label">Логин</label>
<div class="auth__content_has-feedback"
ng-class="{'has-error': loginForm.$submitted && loginForm.login.$invalid}">
<input type="text" name="login" title="login"
placeholder="Введите логин"
class="auth__form-control"
ng-model="vm.user.login"
required
/>
<!-- ERROR MESSAGES -->
<div ng-if="loginForm.$submitted && loginForm.login.$error.required" class="auth__form-group_warning">
Введите логин
</div>
</div>
</div>
<div class="auth__form-group">
<label class="auth__control-label">Пароль</label>
<div class="auth__content_has-feedback auth__content_with-eye"
ng-class="{'has-error': loginForm.$submitted && loginForm.password.$invalid}">
<input type="{{vm.isPasswordVisible ? 'text' : 'password'}}" name="password" title="password"
placeholder="Введите пароль"
class="auth__form-control"
ng-model="vm.user.password"
required
/>
<div class="auth__content_password-mode-switcher">
<label class="auth__content_icon-eye">
<input type="checkbox" ng-model="vm.isPasswordVisible">
</label>
</div>
<!-- ERROR MESSAGES -->
<div ng-if="loginForm.$submitted && loginForm.password.$error.required" class="auth__form-group_warning">
Введите пароль
</div>
</div>
</div>
<div class="auth__form-group" ng-if="vm.error">
<span class="auth__form-group_warning">{{vm.error}}</span>
</div>
<div class="auth__actions">
<button class="auth-btn auth-btn_orange"
type="submit"
ng-disabled="vm.isLoading">
Войти
</button>
</div>
</form>
</div>
import angular from 'angular';
import uiRouter from '@uirouter/angularjs';
// auth core
import AuthUserService from './auth-user.service';
// config
import AuthProvider from './auth.provider';
// http buffer
import AuthHttpBufferService from './auth-http-buffer.service';
// components
import authUserInfo from './auth-user-info/auth-user-info.component';
import authLogin from './auth-login/auth-login.component';
import './styles/auth.css';
import './styles/auth-btn.css';
import './auth-user-info/auth-user-info.css';
export default angular.module('Common.auth', [uiRouter])
// configuration
.provider('commonAuth', AuthProvider)
// constants
.constant('commonAuthEvents', {
loginSuccess: 'common-auth-login-success',
logoutSuccess: 'common-auth-logout-success'
})
// services
.service('commonAuthHttpBuffer', AuthHttpBufferService)
.service('commonAuthUser', AuthUserService)
// components
.component('commonAuthUserInfo', authUserInfo)
.component('commonAuthLogin', authLogin)
.name;
/* eslint-env node */
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const _ = require('lodash');
const path = require('path');
const webpack = require('webpack');
const __DEV__ = process.env.NODE_ENV !== 'production';
function getClientEnvironment() {
const allowedKeys = [
'API_ENV',
'NODE_ENV',
'DISABLED_MONITORS',
'MESSENGER_RECIPIENT'
];
const env = Object.assign(
{},
require('./config/api-env'),
_.pick(process.env, allowedKeys)
);
return {
'process.env': _.mapValues(env, envValue => JSON.stringify(envValue))
};
}
const config = {
cache: true,
context: path.join(__dirname, 'src'),
entry: {
app: './index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: __DEV__ ? 'main.js' : 'main.[hash].js'
},
module: {
rules: [
{
test: /\.js$/,
use: ['babel-loader?cacheDirectory'],
include: [
path.resolve(__dirname, 'src'),
path.resolve(__dirname, 'node_modules/angular-common-auth')
]
},
{
test: /\.html$/,
loader: 'html-loader'
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
})
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'file-loader?name=assets/fonts/[name].[ext]'
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: 'file-loader?name=assets/img/[name].[ext]'
}
]
},
resolve: {
modules: [path.join(__dirname, 'src'), 'node_modules'],
alias: {
components: path.resolve(__dirname, 'src/components'),
enums: path.resolve(__dirname, 'src/enums'),
libs: path.resolve(__dirname, 'src/libs')
}
},
devtool: __DEV__ ? 'cheap-source-map' : 'source-map',
stats: 'errors-only',
devServer: {
contentBase: path.join(__dirname, 'dist'),
port: 3000,
overlay: true,
inline: false,
stats: {
children: false,
assets: false
}
},
plugins: [
new webpack.PrefetchPlugin(
path.join(__dirname, 'src'),
'ng-components/index.js'
),
new ExtractTextPlugin({
filename: __DEV__ ? 'main.css' : 'main.[hash].css',
allChunks: true
}),
new webpack.DefinePlugin(getClientEnvironment()),
new HtmlWebpackPlugin({
template: './index.html',
favicon: './assets/img/favicon.png'
})
]
};
if (!__DEV__) {
// add angular injection annotation to js files
config.module.rules[0].use.unshift('ng-annotate-loader');
// optimise minimise js
config.plugins.push(
new webpack.LoaderOptionsPlugin({
// https://webpack.js.org/guides/migrating/#uglifyjsplugin-minimize-loaders
minimize: true
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true
}),
new webpack.optimize.OccurrenceOrderPlugin()
);
}
module.exports = config;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment