Skip to content

Instantly share code, notes, and snippets.

@adilwali
Created February 26, 2013 17:44
Show Gist options
  • Save adilwali/5040454 to your computer and use it in GitHub Desktop.
Save adilwali/5040454 to your computer and use it in GitHub Desktop.
angular.module('project', ['projectServices'])
.config ($routeProvider) ->
$routeProvider
.when('/login',
templateUrl: 'partials/login.html',
controller: LoginCtrl)
.when('/assignments',
templateUrl: 'partials/assignments.html',
controller: AssignmentListCtrl)
.otherwise(redirectTo: '/login')
.run ($rootScope, $location, User) ->
$rootScope.$on '$routeChangeStart', (event, next, current) ->
if not User.isAuthenticated() and \
next.templateUrl isnt '/partials/login.html'
$location.path("/login")
<p>Welcome, {{User.getName()}}!</p>
<button ng-click="User.logout()">Logout</button>
window.LoginCtrl = ($scope, $location, User) ->
$scope.login = ->
User.login $scope.username, $scope.password, (result) ->
if !result
window.alert('Authentication failed!')
else
$scope.$apply -> $location.path('/assignments')
window.AssignmentListCtrl = ($scope, User) ->
$scope.User = User
moment = require('moment')
action 'index', ->
render(user: request.session.user)
action 'login', ->
authenticate request.body.username, request.body.password, (ret) ->
if (ret)
request.session.user =
name: request.body.username,
time: moment().unix()
send(result: ret)
action 'logout', ->
request.session.destroy()
redirect('/')
<div ng-app="project">
<%- javascript_include_tag('angular', 'angular-resource') %>
<%- js('app') %>
<%- js('controllers') %>
<%- js('services') %>
<div ng-view></div>
</div>
<div>
<form>
<label>Username: <input type="text" ng-model="username"></label>
<label>Password: <input type="password" ng-model="password"></label>
<button ng-click="login()">Login</button>
</form>
</div>
exports.routes = (map)->
map.post '/login', 'home#login'
map.post '/logout', 'home#logout'
map.get '/', 'home#index'
angular.module('projectServices', [])
.factory 'User', ->
@authenticated = false
@name = null
isAuthenticated: => @authenticated
getName: => @name
login: (username, password, callback) =>
$.post '/login',
{username: username, password: password},
((data) =>
if data.result
@name = username
@authenticated = true
callback(data.result)),
'json'
logout: (callback) =>
if @authenticated
$.post '/logout', {},
((data) =>
if data.result
@authenticated = false;
callback(data.result)),
'json'
else callback(false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment