Skip to content

Commit

Permalink
Add auth.
Browse files Browse the repository at this point in the history
  • Loading branch information
mosh-hamedani committed Apr 26, 2017
1 parent 1296f97 commit 7902957
Show file tree
Hide file tree
Showing 11 changed files with 129 additions and 49 deletions.
2 changes: 2 additions & 0 deletions ClientApp/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Auth } from './services/auth.service';
import { BrowserXhr } from '@angular/http';
import { BrowserXhrWithProgress, ProgressService } from './services/progress.service';
import { ViewVehicleComponent } from './components/view-vehicle/view-vehicle';
Expand Down Expand Up @@ -54,6 +55,7 @@ Raven.config('https://d37bba0c459b46e0857e6e2b3aeff09b@sentry.io/155312').instal
providers: [
{ provide: ErrorHandler, useClass: AppErrorHandler },
{ provide: BrowserXhr, useClass: BrowserXhrWithProgress },
Auth,
VehicleService,
PhotoService,
ProgressService
Expand Down
8 changes: 8 additions & 0 deletions ClientApp/app/components/navmenu/navmenu.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@
<div class='clearfix'></div>
<div class='navbar-collapse collapse'>
<ul class='nav navbar-nav'>
<li [routerLinkActive]="['link-active']">
<a href="https://vegaproject.auth0.com/login?client=RfRu3un13aOO73C7X2mH41qxfHRbUc33" *ngIf="!auth.authenticated()">
<span class='glyphicon glyphicon-user'></span> Login
</a>
<a (click)="auth.logout()" *ngIf="auth.authenticated()">
<span class='glyphicon glyphicon-user'></span> Logout
</a>
</li>
<li [routerLinkActive]="['link-active']" [routerLinkActiveOptions]="{exact: true}">
<a [routerLink]="['/vehicles']">
<span class='glyphicon glyphicon-home'></span> Vehicles
Expand Down
2 changes: 2 additions & 0 deletions ClientApp/app/components/navmenu/navmenu.component.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Auth } from './../../services/auth.service';
import { Component } from '@angular/core';

@Component({
Expand All @@ -6,4 +7,5 @@ import { Component } from '@angular/core';
styleUrls: ['./navmenu.component.css']
})
export class NavMenuComponent {
constructor(private auth: Auth) {}
}
51 changes: 51 additions & 0 deletions ClientApp/app/services/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// app/auth.service.ts

import { Injectable } from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';

// Avoid name not found warnings
import Auth0Lock from 'auth0-lock';

@Injectable()
export class Auth {
profile: any;

// Configure Auth0
lock = new Auth0Lock('RfRu3un13aOO73C7X2mH41qxfHRbUc33', 'vegaproject.auth0.com', {});

constructor() {
this.profile = JSON.parse(localStorage.getItem('profile'));

// Add callback for lock `authenticated` event
this.lock.on("authenticated", (authResult) => {
localStorage.setItem('token', authResult.accessToken);

this.lock.getUserInfo(authResult.accessToken, (error, profile) => {
if (error)
throw error;

console.log(profile);
localStorage.setItem('profile', JSON.stringify(profile));
this.profile = profile;
});
});
}

public login() {
// Call the show method to display the widget.
this.lock.show();
}

public authenticated() {
// Check if there's an unexpired JWT
// This searches for an item in localStorage with key == 'token'
return tokenNotExpired('token');
}

public logout() {
// Remove token from localStorage
localStorage.removeItem('token');
localStorage.removeItem('profile');
this.profile = null;
}
}
1 change: 1 addition & 0 deletions Controllers/FeaturesController.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using vega.Controllers.Resources;
Expand Down
4 changes: 4 additions & 0 deletions Controllers/VehiclesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using vega.Controllers.Resources;
using vega.Core.Models;
using vega.Core;
using Microsoft.AspNetCore.Authorization;

namespace vega.Controllers
{
Expand All @@ -25,6 +26,7 @@ public VehiclesController(IMapper mapper, IVehicleRepository repository, IUnitOf
}

[HttpPost]
[Authorize]
public async Task<IActionResult> CreateVehicle([FromBody] SaveVehicleResource vehicleResource)
{
if (!ModelState.IsValid)
Expand All @@ -44,6 +46,7 @@ public async Task<IActionResult> CreateVehicle([FromBody] SaveVehicleResource ve
}

[HttpPut("{id}")]
[Authorize]
public async Task<IActionResult> UpdateVehicle(int id, [FromBody] SaveVehicleResource vehicleResource)
{
if (!ModelState.IsValid)
Expand All @@ -66,6 +69,7 @@ public async Task<IActionResult> UpdateVehicle(int id, [FromBody] SaveVehicleRes
}

[HttpDelete("{id}")]
[Authorize]
public async Task<IActionResult> DeleteVehicle(int id)
{
var vehicle = await repository.GetVehicle(id, includeRelated: false);
Expand Down
103 changes: 55 additions & 48 deletions Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,66 +13,73 @@
namespace Vega
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }
public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<PhotoSettings>(Configuration.GetSection("PhotoSettings"));
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<PhotoSettings>(Configuration.GetSection("PhotoSettings"));

services.AddScoped<IVehicleRepository, VehicleRepository>();
services.AddScoped<IPhotoRepository, PhotoRepository>();
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddScoped<IVehicleRepository, VehicleRepository>();
services.AddScoped<IPhotoRepository, PhotoRepository>();
services.AddScoped<IUnitOfWork, UnitOfWork>();

services.AddAutoMapper();
services.AddAutoMapper();

services.AddDbContext<VegaDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
services.AddDbContext<VegaDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));

// Add framework services.
services.AddMvc();
}
// Add framework services.
services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
if (env.IsDevelopment())
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {
HotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
}

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {
HotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseStaticFiles();
var options = new JwtBearerOptions
{
Audience = "https://api.vega.com",
Authority = "https://vegaproject.auth0.com/"
};
app.UseJwtBearerAuthentication(options);

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
}
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
}
}
}
1 change: 1 addition & 0 deletions Vega.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
<PackageReference Include="AutoMapper" Version="6.0.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="1.2.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.SpaServices" Version="1.1.0" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.0" />
Expand Down
2 changes: 1 addition & 1 deletion Views/Home/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
ViewData["Title"] = "Home Page";
}

<app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>
<app xasp-prerender-module="ClientApp/dist/main-server">Loading...</app>

This comment has been minimized.

Copy link
@ritwickdey

ritwickdey Jan 6, 2018

Hi sir, I've found the fix for the pre-rendering fails.

It is because of node-formidable (I think, it is dependency of Auth0Lock.)

Workaround is here: node-formidable/formidable#337

Just add this line to Webpack configuration .

plugins: [
     new webpack.DefinePlugin({ "global.GENTLY": false })
],

Thank You Sir, for the Awesome Course . I've learned (& still learning - have not completed yet) from the course, specially Application Architecture.


<script src="~/dist/vendor.js" asp-append-version="true"></script>
@section scripts {
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@
"@angular/platform-server": "^2.4.5",
"@angular/router": "^3.4.5",
"@types/node": "^6.0.42",
"angular2-jwt": "^0.2.2",
"angular2-platform-node": "~2.0.11",
"angular2-template-loader": "^0.6.2",
"angular2-universal": "^2.1.0-rc.1",
"angular2-universal-patch": "^0.2.1",
"angular2-universal-polyfills": "^2.1.0-rc.1",
"aspnet-prerendering": "^2.0.0",
"aspnet-webpack": "^1.0.17",
"auth0-lock": "^10.15.0",
"awesome-typescript-loader": "^3.0.0",
"bootstrap": "^3.3.7",
"css": "^2.2.1",
Expand Down
2 changes: 2 additions & 0 deletions webpack.config.vendor.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ module.exports = (env) => {
'@angular/platform-browser-dynamic',
'@angular/router',
'@angular/platform-server',
'angular2-jwt',
'angular2-universal',
'angular2-universal-polyfills',
'auth0-lock',
'bootstrap',
'bootstrap/dist/css/bootstrap.css',
'es6-shim',
Expand Down

0 comments on commit 7902957

Please sign in to comment.