diff --git a/examples/angular/with-passwordless/server/api-server.js b/examples/angular/with-passwordless/server/api-server.js new file mode 100644 index 00000000..61f859db --- /dev/null +++ b/examples/angular/with-passwordless/server/api-server.js @@ -0,0 +1,70 @@ +const express = require("express"); +const cors = require("cors"); + +const supertokens = require("supertokens-node"); +const { middleware, errorHandler } = require("supertokens-node/framework/express"); +const Session = require("supertokens-node/recipe/session"); +const Passwordless = require("supertokens-node/recipe/passwordless"); +const { verifySession } = require("supertokens-node/recipe/session/framework/express"); + + +supertokens.init({ + framework: "express", + supertokens: { + // These are the connection details of the app you created on supertokens.com + connectionURI: "https://try.supertokens.com", + // apiKey: "", + }, + appInfo: { + // learn more about this on https://supertokens.com/docs/session/appinfo + appName: "My App", + apiDomain: "http://localhost:3000", + websiteDomain: "http://localhost:4200", + apiBasePath: "/api", + websiteBasePath: "/auth" + }, + recipeList: [ + Passwordless.init({ + flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", + contactMethod: "EMAIL" + }), + Session.init() // initializes session features + ] +}); + +var app = express(); + +//CORS policies for supertokens +app.use( + cors({ + origin: "http://localhost:4200", + allowedHeaders: ["content-type", ...supertokens.getAllCORSHeaders()], + credentials: true + }) +); +app.use(middleware()); + +app.use(errorHandler()); + +app.use(function(req, res, next){ + console.log(req.url); + console.log(req.headers); + console.log(req.body || (req.method + " method")); +}) + +app.get("/get-user-info", verifySession(), async (req, res) => { + console.log("Getting user info..."); + let userId = req.session.getUserId(); + try { + let userInfo = await Passwordless.getUserById({userId}); + return res.status(200).send(userInfo); + } catch(err){ + console.log(err) + return res.status(500).send("Some error in getting the user info") + } +}) + + +var listener = app.listen(3000, async () => { + console.log("Listening on port " + listener.address().port); +}); \ No newline at end of file diff --git a/examples/angular/with-passwordless/server/package.json b/examples/angular/with-passwordless/server/package.json new file mode 100644 index 00000000..6ecd4a36 --- /dev/null +++ b/examples/angular/with-passwordless/server/package.json @@ -0,0 +1,17 @@ +{ + "name": "api-server", + "version": "1.0.0", + "description": "", + "main": "api-server.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "start": "node api-server.js" + }, + "author": "", + "license": "MIT", + "dependencies": { + "cors": "^2.8.5", + "express": "^4.18.1", + "supertokens-node": "^11.0.3" + } +} diff --git a/examples/angular/with-passwordless/ui/README.md b/examples/angular/with-passwordless/ui/README.md new file mode 100644 index 00000000..ad3d0730 --- /dev/null +++ b/examples/angular/with-passwordless/ui/README.md @@ -0,0 +1,27 @@ +# Ui + +This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 11.2.12. + +## Development server + +Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. + +## Code scaffolding + +Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. + +## Build + +Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. + +## Running unit tests + +Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). + +## Running end-to-end tests + +Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). + +## Further help + +To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page. diff --git a/examples/angular/with-passwordless/ui/angular.json b/examples/angular/with-passwordless/ui/angular.json new file mode 100644 index 00000000..8df9dd72 --- /dev/null +++ b/examples/angular/with-passwordless/ui/angular.json @@ -0,0 +1,124 @@ +{ + "$schema": "./node_modules/@angular/cli/lib/config/schema.json", + "version": 1, + "newProjectRoot": "projects", + "projects": { + "ui": { + "projectType": "application", + "schematics": {}, + "root": "", + "sourceRoot": "src", + "prefix": "app", + "architect": { + "build": { + "builder": "@angular-devkit/build-angular:browser", + "options": { + "outputPath": "dist/ui", + "index": "src/index.html", + "main": "src/main.ts", + "polyfills": "src/polyfills.ts", + "tsConfig": "tsconfig.app.json", + "aot": true, + "assets": [ + "src/favicon.ico", + "src/assets" + ], + "styles": [ + "src/styles.css" + ], + "scripts": [] + }, + "configurations": { + "production": { + "fileReplacements": [ + { + "replace": "src/environments/environment.ts", + "with": "src/environments/environment.prod.ts" + } + ], + "optimization": true, + "outputHashing": "all", + "sourceMap": false, + "namedChunks": false, + "extractLicenses": true, + "vendorChunk": false, + "buildOptimizer": true, + "budgets": [ + { + "type": "initial", + "maximumWarning": "2mb", + "maximumError": "5mb" + }, + { + "type": "anyComponentStyle", + "maximumWarning": "6kb", + "maximumError": "10kb" + } + ] + } + } + }, + "serve": { + "builder": "@angular-devkit/build-angular:dev-server", + "options": { + "browserTarget": "ui:build" + }, + "configurations": { + "production": { + "browserTarget": "ui:build:production" + } + } + }, + "extract-i18n": { + "builder": "@angular-devkit/build-angular:extract-i18n", + "options": { + "browserTarget": "ui:build" + } + }, + "test": { + "builder": "@angular-devkit/build-angular:karma", + "options": { + "main": "src/test.ts", + "polyfills": "src/polyfills.ts", + "tsConfig": "tsconfig.spec.json", + "karmaConfig": "karma.conf.js", + "assets": [ + "src/favicon.ico", + "src/assets" + ], + "styles": [ + "src/styles.css" + ], + "scripts": [] + } + }, + "lint": { + "builder": "@angular-devkit/build-angular:tslint", + "options": { + "tsConfig": [ + "tsconfig.app.json", + "tsconfig.spec.json", + "e2e/tsconfig.json" + ], + "exclude": [ + "**/node_modules/**" + ] + } + }, + "e2e": { + "builder": "@angular-devkit/build-angular:protractor", + "options": { + "protractorConfig": "e2e/protractor.conf.js", + "devServerTarget": "ui:serve" + }, + "configurations": { + "production": { + "devServerTarget": "ui:serve:production" + } + } + } + } + } + }, + "defaultProject": "ui" +} diff --git a/examples/angular/with-passwordless/ui/e2e/protractor.conf.js b/examples/angular/with-passwordless/ui/e2e/protractor.conf.js new file mode 100644 index 00000000..361e7f0c --- /dev/null +++ b/examples/angular/with-passwordless/ui/e2e/protractor.conf.js @@ -0,0 +1,37 @@ +// @ts-check +// Protractor configuration file, see link for more information +// https://github.com/angular/protractor/blob/master/lib/config.ts + +const { SpecReporter, StacktraceOption } = require('jasmine-spec-reporter'); + +/** + * @type { import("protractor").Config } + */ +exports.config = { + allScriptsTimeout: 11000, + specs: [ + './src/**/*.e2e-spec.ts' + ], + capabilities: { + browserName: 'chrome' + }, + directConnect: true, + SELENIUM_PROMISE_MANAGER: false, + baseUrl: 'http://localhost:4200/', + framework: 'jasmine', + jasmineNodeOpts: { + showColors: true, + defaultTimeoutInterval: 30000, + print: function() {} + }, + onPrepare() { + require('ts-node').register({ + project: require('path').join(__dirname, './tsconfig.json') + }); + jasmine.getEnv().addReporter(new SpecReporter({ + spec: { + displayStacktrace: StacktraceOption.PRETTY + } + })); + } +}; \ No newline at end of file diff --git a/examples/angular/with-passwordless/ui/e2e/src/app.e2e-spec.ts b/examples/angular/with-passwordless/ui/e2e/src/app.e2e-spec.ts new file mode 100644 index 00000000..2066e4d4 --- /dev/null +++ b/examples/angular/with-passwordless/ui/e2e/src/app.e2e-spec.ts @@ -0,0 +1,23 @@ +import { browser, logging } from 'protractor'; +import { AppPage } from './app.po'; + +describe('workspace-project App', () => { + let page: AppPage; + + beforeEach(() => { + page = new AppPage(); + }); + + it('should display welcome message', async () => { + await page.navigateTo(); + expect(await page.getTitleText()).toEqual('ui app is running!'); + }); + + afterEach(async () => { + // Assert that there are no errors emitted from the browser + const logs = await browser.manage().logs().get(logging.Type.BROWSER); + expect(logs).not.toContain(jasmine.objectContaining({ + level: logging.Level.SEVERE, + } as logging.Entry)); + }); +}); diff --git a/examples/angular/with-passwordless/ui/e2e/src/app.po.ts b/examples/angular/with-passwordless/ui/e2e/src/app.po.ts new file mode 100644 index 00000000..c9c85ab9 --- /dev/null +++ b/examples/angular/with-passwordless/ui/e2e/src/app.po.ts @@ -0,0 +1,11 @@ +import { browser, by, element } from 'protractor'; + +export class AppPage { + async navigateTo(): Promise { + return browser.get(browser.baseUrl); + } + + async getTitleText(): Promise { + return element(by.css('app-root .content span')).getText(); + } +} diff --git a/examples/angular/with-passwordless/ui/e2e/tsconfig.json b/examples/angular/with-passwordless/ui/e2e/tsconfig.json new file mode 100644 index 00000000..0782539c --- /dev/null +++ b/examples/angular/with-passwordless/ui/e2e/tsconfig.json @@ -0,0 +1,13 @@ +/* To learn more about this file see: https://angular.io/config/tsconfig. */ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/e2e", + "module": "commonjs", + "target": "es2018", + "types": [ + "jasmine", + "node" + ] + } +} diff --git a/examples/angular/with-passwordless/ui/karma.conf.js b/examples/angular/with-passwordless/ui/karma.conf.js new file mode 100644 index 00000000..c20937c5 --- /dev/null +++ b/examples/angular/with-passwordless/ui/karma.conf.js @@ -0,0 +1,44 @@ +// Karma configuration file, see link for more information +// https://karma-runner.github.io/1.0/config/configuration-file.html + +module.exports = function (config) { + config.set({ + basePath: '', + frameworks: ['jasmine', '@angular-devkit/build-angular'], + plugins: [ + require('karma-jasmine'), + require('karma-chrome-launcher'), + require('karma-jasmine-html-reporter'), + require('karma-coverage'), + require('@angular-devkit/build-angular/plugins/karma') + ], + client: { + jasmine: { + // you can add configuration options for Jasmine here + // the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html + // for example, you can disable the random execution with `random: false` + // or set a specific seed with `seed: 4321` + }, + clearContext: false // leave Jasmine Spec Runner output visible in browser + }, + jasmineHtmlReporter: { + suppressAll: true // removes the duplicated traces + }, + coverageReporter: { + dir: require('path').join(__dirname, './coverage/ui'), + subdir: '.', + reporters: [ + { type: 'html' }, + { type: 'text-summary' } + ] + }, + reporters: ['progress', 'kjhtml'], + port: 9876, + colors: true, + logLevel: config.LOG_INFO, + autoWatch: true, + browsers: ['Chrome'], + singleRun: false, + restartOnFileChange: true + }); +}; diff --git a/examples/angular/with-passwordless/ui/package.json b/examples/angular/with-passwordless/ui/package.json new file mode 100644 index 00000000..8e3e6741 --- /dev/null +++ b/examples/angular/with-passwordless/ui/package.json @@ -0,0 +1,46 @@ +{ + "name": "ui", + "version": "0.0.0", + "scripts": { + "ng": "ng", + "start": "ng serve", + "build": "ng build", + "test": "ng test", + "lint": "ng lint", + "e2e": "ng e2e" + }, + "private": true, + "dependencies": { + "@angular/animations": "~11.2.13", + "@angular/common": "~11.2.13", + "@angular/compiler": "~11.2.13", + "@angular/core": "~11.2.13", + "@angular/forms": "~11.2.13", + "@angular/platform-browser": "~11.2.13", + "@angular/platform-browser-dynamic": "~11.2.13", + "@angular/router": "~11.2.13", + "rxjs": "~6.6.0", + "supertokens-web-js": "^0.1.4", + "tslib": "^2.0.0", + "zone.js": "~0.11.3" + }, + "devDependencies": { + "@angular-devkit/build-angular": "~0.1102.12", + "@angular/cli": "~11.2.12", + "@angular/compiler-cli": "~11.2.13", + "@types/jasmine": "~3.6.0", + "@types/node": "^12.11.1", + "codelyzer": "^6.0.0", + "jasmine-core": "~3.6.0", + "jasmine-spec-reporter": "~5.0.0", + "karma": "~6.1.0", + "karma-chrome-launcher": "~3.1.0", + "karma-coverage": "~2.0.3", + "karma-jasmine": "~4.0.0", + "karma-jasmine-html-reporter": "^1.5.0", + "protractor": "~7.0.0", + "ts-node": "~8.3.0", + "tslint": "~6.1.0", + "typescript": "~4.1.5" + } +} diff --git a/examples/angular/with-passwordless/ui/src/app/app-routing.module.ts b/examples/angular/with-passwordless/ui/src/app/app-routing.module.ts new file mode 100644 index 00000000..a48aa3b8 --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/app-routing.module.ts @@ -0,0 +1,17 @@ +import { NgModule } from '@angular/core'; +import { RouterModule, Routes } from '@angular/router'; +import { DashboardComponent } from './dashboard/dashboard.component'; +import { LoginWithLinkComponent } from './login-with-link/login-with-link.component'; +import { LoginComponent } from './login/login.component'; + +const routes: Routes = [ + { path: 'login', component: LoginComponent }, + { path: 'dashboard', component: DashboardComponent }, + { path: 'auth/verify', component: LoginWithLinkComponent } +]; + +@NgModule({ + imports: [RouterModule.forRoot(routes)], + exports: [RouterModule] +}) +export class AppRoutingModule { } \ No newline at end of file diff --git a/examples/angular/with-passwordless/ui/src/app/app.component.css b/examples/angular/with-passwordless/ui/src/app/app.component.css new file mode 100644 index 00000000..e69de29b diff --git a/examples/angular/with-passwordless/ui/src/app/app.component.html b/examples/angular/with-passwordless/ui/src/app/app.component.html new file mode 100644 index 00000000..65b1a330 --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/app.component.html @@ -0,0 +1,17 @@ + + + {{ title }} + + + + +

{{ title }}

+ + + + + \ No newline at end of file diff --git a/examples/angular/with-passwordless/ui/src/app/app.component.spec.ts b/examples/angular/with-passwordless/ui/src/app/app.component.spec.ts new file mode 100644 index 00000000..daa24cce --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/app.component.spec.ts @@ -0,0 +1,35 @@ +import { TestBed } from '@angular/core/testing'; +import { RouterTestingModule } from '@angular/router/testing'; +import { AppComponent } from './app.component'; + +describe('AppComponent', () => { + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [ + RouterTestingModule + ], + declarations: [ + AppComponent + ], + }).compileComponents(); + }); + + it('should create the app', () => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.componentInstance; + expect(app).toBeTruthy(); + }); + + it(`should have as title 'ui'`, () => { + const fixture = TestBed.createComponent(AppComponent); + const app = fixture.componentInstance; + expect(app.title).toEqual('ui'); + }); + + it('should render title', () => { + const fixture = TestBed.createComponent(AppComponent); + fixture.detectChanges(); + const compiled = fixture.nativeElement; + expect(compiled.querySelector('.content span').textContent).toContain('ui app is running!'); + }); +}); diff --git a/examples/angular/with-passwordless/ui/src/app/app.component.ts b/examples/angular/with-passwordless/ui/src/app/app.component.ts new file mode 100644 index 00000000..78da5de8 --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/app.component.ts @@ -0,0 +1,12 @@ +import { Component } from '@angular/core'; +import { environment } from '../environments/environment' + +@Component({ + selector: 'app-root', + templateUrl: './app.component.html', + styleUrls: ['./app.component.css'] +}) + +export class AppComponent { + title = environment.appName; +} \ No newline at end of file diff --git a/examples/angular/with-passwordless/ui/src/app/app.module.ts b/examples/angular/with-passwordless/ui/src/app/app.module.ts new file mode 100644 index 00000000..5f53a122 --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/app.module.ts @@ -0,0 +1,30 @@ +import { NgModule } from '@angular/core'; +import { BrowserModule } from '@angular/platform-browser'; + +import { AppRoutingModule } from './app-routing.module'; +import { AppComponent } from './app.component'; +import { LoginComponent } from './login/login.component'; +import { DashboardComponent } from './dashboard/dashboard.component'; +import { FormsModule } from '@angular/forms'; +import { LoginCodeComponent } from './login-code/login-code.component'; +import { LoginWithLinkComponent } from './login-with-link/login-with-link.component'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + declarations: [ + AppComponent, + LoginComponent, + DashboardComponent, + LoginCodeComponent, + LoginWithLinkComponent + ], + imports: [ + BrowserModule, + AppRoutingModule, + FormsModule, + HttpClientModule + ], + providers: [], + bootstrap: [AppComponent] +}) +export class AppModule { } diff --git a/examples/angular/with-passwordless/ui/src/app/auth.service.spec.ts b/examples/angular/with-passwordless/ui/src/app/auth.service.spec.ts new file mode 100644 index 00000000..f1251cac --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/auth.service.spec.ts @@ -0,0 +1,16 @@ +import { TestBed } from '@angular/core/testing'; + +import { AuthService } from './auth.service'; + +describe('AuthService', () => { + let service: AuthService; + + beforeEach(() => { + TestBed.configureTestingModule({}); + service = TestBed.inject(AuthService); + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); +}); diff --git a/examples/angular/with-passwordless/ui/src/app/auth.service.ts b/examples/angular/with-passwordless/ui/src/app/auth.service.ts new file mode 100644 index 00000000..81f23c2a --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/auth.service.ts @@ -0,0 +1,117 @@ +import { Injectable } from '@angular/core'; +import SuperTokens from 'supertokens-web-js'; +import Session from 'supertokens-web-js/recipe/session'; +import Passwordless from 'supertokens-web-js/recipe/passwordless'; +import { environment } from '../environments/environment'; + +@Injectable({ + providedIn: 'root' +}) +export class AuthService { + + constructor() { + this.configureAuth(); + } + + configureAuth(){ + SuperTokens.init({ + appInfo: { + apiDomain: environment.apiDomain, + apiBasePath: environment.apiBasePath, + appName: environment.appName, + }, + recipeList: [ + Session.init({ + onHandleEvent: (context) => { + if (context.action === "UNAUTHORISED") { + // called when the user doesn't have a valid session but made a request that requires one + // NOTE: This event can fire multiple times + console.log("xxxxxx----Unauthorized----xxxxxx"); + if (context.sessionExpiredOrRevoked) { + // the sessionExpiredOrRevoked property is set to true if the current call cleared the session from storage + // this happens only once, even if multiple tabs sharing the same session are open, making it useful for analytics purposes + console.log("xxxxxx----Session Expired----xxxxxx"); + } + } + }, + }), + Passwordless.init(), + ], + }); + } + + authenticate() : Promise { + return Session.doesSessionExist().then((isValidSession) => { + return isValidSession; + }).catch((err) => { + throw new Error(err); + }) + } + + + getUserIdAndPayload() : Promise { + return Session.doesSessionExist().then((exists) => { + if(!exists){ + throw Error("No session exists") + } + return exists; + }).then((exists) => { + return Session.getUserId().then((userId) => { + return userId; + }) + }).then((userId) => { + return Session.getAccessTokenPayloadSecurely().then((payload) => { + return { userId, payload } + }) + }).catch((err) => { + throw new Error(err); + }) + } + + /** + * Call the backend API to email a unique code or magic link. Uses supertokens-web-js sdk function to do this. + * @param inputs { email?: string } + */ + sendCode(inputs: { email?: string }): Promise{ + if(!inputs || !inputs.hasOwnProperty("email")){ + return Promise.reject("Invalid input. Please provide email."); + } + return Passwordless.createCode({ email: inputs.email }).then((response) => { + if(response && response.status=="OK"){ + return "Please check your mailbox for the login code"; + } else { + throw new Error(response.status || response.fetchResponse.statusText); + } + }); + } + + consumeCode(inputs: { userInputCode?: string }): Promise{ + if(!inputs || !inputs.hasOwnProperty("userInputCode")){ + return Promise.reject("Invalid input. Please provide login code."); + } + return Passwordless.consumeCode({ userInputCode: inputs.userInputCode }).then((response) => { + if(response && response.status=="OK" && response.user){ + return "Login successful"; + } else { + throw new Error(response.status || response.fetchResponse.statusText); + // Promise.reject(response.fetchResponse.statusText); + } + }) + } + + consumeCodeFromLink(){ + return Passwordless.consumeCode({}).then((response) => { + if(response && response.status=="OK" && response.user){ + return "Login successful"; + } else { + throw new Error(response.status || response.fetchResponse.statusText); + // Promise.reject(response.fetchResponse.statusText); + } + }) + } + + logout(){ + return Passwordless.signOut(); + } + +} diff --git a/examples/angular/with-passwordless/ui/src/app/dashboard/dashboard.component.css b/examples/angular/with-passwordless/ui/src/app/dashboard/dashboard.component.css new file mode 100644 index 00000000..e69de29b diff --git a/examples/angular/with-passwordless/ui/src/app/dashboard/dashboard.component.html b/examples/angular/with-passwordless/ui/src/app/dashboard/dashboard.component.html new file mode 100644 index 00000000..c29bdc77 --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/dashboard/dashboard.component.html @@ -0,0 +1,6 @@ +

Logged in {{ user ? user.email : "" }} successfully! +
+ Your user id is : {{ user.userId }} +

+ +Logout \ No newline at end of file diff --git a/examples/angular/with-passwordless/ui/src/app/dashboard/dashboard.component.spec.ts b/examples/angular/with-passwordless/ui/src/app/dashboard/dashboard.component.spec.ts new file mode 100644 index 00000000..5ec4ff8f --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/dashboard/dashboard.component.spec.ts @@ -0,0 +1,25 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { DashboardComponent } from './dashboard.component'; + +describe('DashboardComponent', () => { + let component: DashboardComponent; + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + declarations: [ DashboardComponent ] + }) + .compileComponents(); + }); + + beforeEach(() => { + fixture = TestBed.createComponent(DashboardComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/examples/angular/with-passwordless/ui/src/app/dashboard/dashboard.component.ts b/examples/angular/with-passwordless/ui/src/app/dashboard/dashboard.component.ts new file mode 100644 index 00000000..dc4232e4 --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/dashboard/dashboard.component.ts @@ -0,0 +1,45 @@ +import { Component, OnInit } from '@angular/core'; +import { Router } from '@angular/router'; +import { AuthService } from '../auth.service'; +import { UserService } from '../user.service'; + +@Component({ + selector: 'app-dashboard', + templateUrl: './dashboard.component.html', + styleUrls: ['./dashboard.component.css'] +}) +export class DashboardComponent implements OnInit { + + user: { email?: string, userId?: string } = {}; + + constructor(private router: Router, private authService: AuthService, private userService: UserService) { + } + + ngOnInit(): void { + this.authService.getUserIdAndPayload().then((userAndPayloadInfo) => { + console.log(JSON.stringify(userAndPayloadInfo)); + Object.assign(this.user, userAndPayloadInfo); + }).catch((err) => { + console.log(err); + this.router.navigate["/login"]; + }) + // this.userService.getUser().subscribe({ + // next: (user: Object) => { + // console.log(user); + // }, + // error: (error: any) => { + // console.log(error); + // } + // }) + } + + logout(){ + console.log("Logging out"); + this.authService.logout().then(() => { + this.router.navigate(["/login"]); + }).catch(() => { + console.log("Enter again or resend code"); + }) + } + +} diff --git a/examples/angular/with-passwordless/ui/src/app/login-code/login-code.component.css b/examples/angular/with-passwordless/ui/src/app/login-code/login-code.component.css new file mode 100644 index 00000000..e69de29b diff --git a/examples/angular/with-passwordless/ui/src/app/login-code/login-code.component.html b/examples/angular/with-passwordless/ui/src/app/login-code/login-code.component.html new file mode 100644 index 00000000..3f27e5d7 --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/login-code/login-code.component.html @@ -0,0 +1,8 @@ +
+ {{successText}} + {{errorText}} +
+ +

+ +
\ No newline at end of file diff --git a/examples/angular/with-passwordless/ui/src/app/login-code/login-code.component.spec.ts b/examples/angular/with-passwordless/ui/src/app/login-code/login-code.component.spec.ts new file mode 100644 index 00000000..9bdb225f --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/login-code/login-code.component.spec.ts @@ -0,0 +1,25 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { LoginCodeComponent } from './login-code.component'; + +describe('LoginCodeComponent', () => { + let component: LoginCodeComponent; + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + declarations: [ LoginCodeComponent ] + }) + .compileComponents(); + }); + + beforeEach(() => { + fixture = TestBed.createComponent(LoginCodeComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/examples/angular/with-passwordless/ui/src/app/login-code/login-code.component.ts b/examples/angular/with-passwordless/ui/src/app/login-code/login-code.component.ts new file mode 100644 index 00000000..159ab88e --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/login-code/login-code.component.ts @@ -0,0 +1,41 @@ +import { Component, OnInit } from '@angular/core'; +import { Router } from '@angular/router'; +import { AuthService } from '../auth.service'; + +@Component({ + selector: 'app-login-code', + templateUrl: './login-code.component.html', + styleUrls: ['./login-code.component.css'] +}) +export class LoginCodeComponent implements OnInit { + + +userInputCode: string = ""; + successText: string = ""; + errorText: string = ""; + isValidCode: boolean = false; + + constructor(private router: Router, private authService: AuthService) { + } + + ngOnInit(): void { + } + + onSubmit(inputs: { userInputCode?: string }){ + this.authService.consumeCode(inputs).then((successText) => { + // User authenticated. Redirect to the next page. + this.successText = successText; + this.errorText = ""; + this.isValidCode = true; + this.router.navigate(["/dashboard"]); + }).catch((err) => { + // Set the error message + console.log("Error in verifying code"); + console.log(err); + this.errorText = err; + this.successText = ""; + this.isValidCode = false; + }) + } + +} diff --git a/examples/angular/with-passwordless/ui/src/app/login-with-link/login-with-link.component.css b/examples/angular/with-passwordless/ui/src/app/login-with-link/login-with-link.component.css new file mode 100644 index 00000000..e69de29b diff --git a/examples/angular/with-passwordless/ui/src/app/login-with-link/login-with-link.component.html b/examples/angular/with-passwordless/ui/src/app/login-with-link/login-with-link.component.html new file mode 100644 index 00000000..f276bc35 --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/login-with-link/login-with-link.component.html @@ -0,0 +1 @@ +

Logging you in...

diff --git a/examples/angular/with-passwordless/ui/src/app/login-with-link/login-with-link.component.spec.ts b/examples/angular/with-passwordless/ui/src/app/login-with-link/login-with-link.component.spec.ts new file mode 100644 index 00000000..8da1e8ef --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/login-with-link/login-with-link.component.spec.ts @@ -0,0 +1,25 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { LoginWithLinkComponent } from './login-with-link.component'; + +describe('LoginWithLinkComponent', () => { + let component: LoginWithLinkComponent; + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + declarations: [ LoginWithLinkComponent ] + }) + .compileComponents(); + }); + + beforeEach(() => { + fixture = TestBed.createComponent(LoginWithLinkComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/examples/angular/with-passwordless/ui/src/app/login-with-link/login-with-link.component.ts b/examples/angular/with-passwordless/ui/src/app/login-with-link/login-with-link.component.ts new file mode 100644 index 00000000..012ed815 --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/login-with-link/login-with-link.component.ts @@ -0,0 +1,28 @@ +import { Component, OnInit } from '@angular/core'; +import { Router } from '@angular/router'; +import { AuthService } from '../auth.service'; + +@Component({ + selector: 'app-login-with-link', + templateUrl: './login-with-link.component.html', + styleUrls: ['./login-with-link.component.css'] +}) +export class LoginWithLinkComponent implements OnInit { + + constructor(private router: Router, private authService: AuthService) { + } + + ngOnInit(): void { + // Automatically picks the code from the link in address bar and authenticates + this.authService.consumeCodeFromLink().then((successText) => { + // User authenticated. Redirect to the next page. + this.router.navigate(["/dashboard"]); + }).catch((err) => { + // Set the error message + console.log("Error in verifying code"); + console.log(err); + this.router.navigate(["/login"], { state: { errorText: err }}); + }) + } + +} diff --git a/examples/angular/with-passwordless/ui/src/app/login/login.component.css b/examples/angular/with-passwordless/ui/src/app/login/login.component.css new file mode 100644 index 00000000..e69de29b diff --git a/examples/angular/with-passwordless/ui/src/app/login/login.component.html b/examples/angular/with-passwordless/ui/src/app/login/login.component.html new file mode 100644 index 00000000..5c9c2350 --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/login/login.component.html @@ -0,0 +1,13 @@ +
+ {{errorText}} +
+ + Resend code +
+ + {{successText}} +
+
+
+ + \ No newline at end of file diff --git a/examples/angular/with-passwordless/ui/src/app/login/login.component.spec.ts b/examples/angular/with-passwordless/ui/src/app/login/login.component.spec.ts new file mode 100644 index 00000000..d2c0e6c8 --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/login/login.component.spec.ts @@ -0,0 +1,25 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { LoginComponent } from './login.component'; + +describe('LoginComponent', () => { + let component: LoginComponent; + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + declarations: [ LoginComponent ] + }) + .compileComponents(); + }); + + beforeEach(() => { + fixture = TestBed.createComponent(LoginComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/examples/angular/with-passwordless/ui/src/app/login/login.component.ts b/examples/angular/with-passwordless/ui/src/app/login/login.component.ts new file mode 100644 index 00000000..67e7413b --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/login/login.component.ts @@ -0,0 +1,39 @@ +import { Component, OnInit } from '@angular/core'; +import { Router } from '@angular/router'; +import { AuthService } from '../auth.service'; + +@Component({ + selector: 'app-login', + templateUrl: './login.component.html', + styleUrls: ['./login.component.css'] +}) +export class LoginComponent implements OnInit { + + email: string = ""; + errorText: string = ""; + successText: string = ""; + isCodeDelivered: boolean = false; + + constructor(private router: Router, private authService: AuthService) { + if(this.router.getCurrentNavigation().extras.state && this.router.getCurrentNavigation().extras.state.errorText){ + this.errorText = this.router.getCurrentNavigation().extras.state.errorText; + } + } + + ngOnInit(): void { + } + + onSubmit(inputs: { email?: string }){ + this.authService.sendCode(inputs).then((successText) => { + this.successText = successText; + this.errorText = ""; + this.isCodeDelivered = true; // Show the input field to enter code now + }).catch((err) => { + // Set the error message + this.errorText = err; + this.successText = ""; + this.isCodeDelivered = false; // Hide the input field to enter code now + }) + } + +} diff --git a/examples/angular/with-passwordless/ui/src/app/user.service.spec.ts b/examples/angular/with-passwordless/ui/src/app/user.service.spec.ts new file mode 100644 index 00000000..3f804c9f --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/user.service.spec.ts @@ -0,0 +1,16 @@ +import { TestBed } from '@angular/core/testing'; + +import { UserService } from './user.service'; + +describe('UserService', () => { + let service: UserService; + + beforeEach(() => { + TestBed.configureTestingModule({}); + service = TestBed.inject(UserService); + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); +}); diff --git a/examples/angular/with-passwordless/ui/src/app/user.service.ts b/examples/angular/with-passwordless/ui/src/app/user.service.ts new file mode 100644 index 00000000..28ce6929 --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/app/user.service.ts @@ -0,0 +1,16 @@ +import { Injectable } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { Observable } from 'rxjs'; + +@Injectable({ + providedIn: 'root' +}) +export class UserService { + + constructor(private http: HttpClient) { } + + getUser(): Observable{ + return this.http.get("http://localhost:3000/get-user-info", { withCredentials: true }); + } + +} diff --git a/examples/angular/with-passwordless/ui/src/environments/environment.prod.ts b/examples/angular/with-passwordless/ui/src/environments/environment.prod.ts new file mode 100644 index 00000000..3612073b --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/environments/environment.prod.ts @@ -0,0 +1,3 @@ +export const environment = { + production: true +}; diff --git a/examples/angular/with-passwordless/ui/src/environments/environment.ts b/examples/angular/with-passwordless/ui/src/environments/environment.ts new file mode 100644 index 00000000..bf31652d --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/environments/environment.ts @@ -0,0 +1,19 @@ +// This file can be replaced during build by using the `fileReplacements` array. +// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. +// The list of file replacements can be found in `angular.json`. + +export const environment = { + production: false, + apiDomain: "http://localhost:3000", + apiBasePath: "/api", + appName: "SuperTokens Passwordless Demo - Angular" +}; + +/* + * For easier debugging in development mode, you can import the following file + * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. + * + * This import should be commented out in production mode because it will have a negative impact + * on performance if an error is thrown. + */ +// import 'zone.js/dist/zone-error'; // Included with Angular CLI. diff --git a/examples/angular/with-passwordless/ui/src/favicon.ico b/examples/angular/with-passwordless/ui/src/favicon.ico new file mode 100644 index 00000000..997406ad Binary files /dev/null and b/examples/angular/with-passwordless/ui/src/favicon.ico differ diff --git a/examples/angular/with-passwordless/ui/src/index.html b/examples/angular/with-passwordless/ui/src/index.html new file mode 100644 index 00000000..e4a618e1 --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/index.html @@ -0,0 +1,13 @@ + + + + + Ui + + + + + + + + diff --git a/examples/angular/with-passwordless/ui/src/main.ts b/examples/angular/with-passwordless/ui/src/main.ts new file mode 100644 index 00000000..c7b673cf --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/main.ts @@ -0,0 +1,12 @@ +import { enableProdMode } from '@angular/core'; +import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; + +import { AppModule } from './app/app.module'; +import { environment } from './environments/environment'; + +if (environment.production) { + enableProdMode(); +} + +platformBrowserDynamic().bootstrapModule(AppModule) + .catch(err => console.error(err)); diff --git a/examples/angular/with-passwordless/ui/src/polyfills.ts b/examples/angular/with-passwordless/ui/src/polyfills.ts new file mode 100644 index 00000000..d5f67bd9 --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/polyfills.ts @@ -0,0 +1,65 @@ +/** + * This file includes polyfills needed by Angular and is loaded before the app. + * You can add your own extra polyfills to this file. + * + * This file is divided into 2 sections: + * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. + * 2. Application imports. Files imported after ZoneJS that should be loaded before your main + * file. + * + * The current setup is for so-called "evergreen" browsers; the last versions of browsers that + * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), + * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. + * + * Learn more in https://angular.io/guide/browser-support + */ + +/*************************************************************************************************** + * BROWSER POLYFILLS + */ + +/** + * IE11 requires the following for NgClass support on SVG elements + */ +// import 'classlist.js'; // Run `npm install --save classlist.js`. + +/** + * Web Animations `@angular/platform-browser/animations` + * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. + * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). + */ +// import 'web-animations-js'; // Run `npm install --save web-animations-js`. + +/** + * By default, zone.js will patch all possible macroTask and DomEvents + * user can disable parts of macroTask/DomEvents patch by setting following flags + * because those flags need to be set before `zone.js` being loaded, and webpack + * will put import in the top of bundle, so user need to create a separate file + * in this directory (for example: zone-flags.ts), and put the following flags + * into that file, and then add the following code before importing zone.js. + * import './zone-flags'; + * + * The flags allowed in zone-flags.ts are listed here. + * + * The following flags will work for all browsers. + * + * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame + * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick + * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames + * + * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js + * with the following flag, it will bypass `zone.js` patch for IE/Edge + * + * (window as any).__Zone_enable_cross_context_check = true; + * + */ + +/*************************************************************************************************** + * Zone JS is required by default for Angular itself. + */ +import 'zone.js/dist/zone'; // Included with Angular CLI. + + +/*************************************************************************************************** + * APPLICATION IMPORTS + */ diff --git a/examples/angular/with-passwordless/ui/src/styles.css b/examples/angular/with-passwordless/ui/src/styles.css new file mode 100644 index 00000000..15be50e4 --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/styles.css @@ -0,0 +1,15 @@ +/* You can add global styles to this file, and also import other style files */ + +a { + cursor: pointer; + color: blue; + text-decoration: underline; +} + +.success { + color: green; +} + +.error { + color: red; +} \ No newline at end of file diff --git a/examples/angular/with-passwordless/ui/src/test.ts b/examples/angular/with-passwordless/ui/src/test.ts new file mode 100644 index 00000000..50193eb0 --- /dev/null +++ b/examples/angular/with-passwordless/ui/src/test.ts @@ -0,0 +1,25 @@ +// This file is required by karma.conf.js and loads recursively all the .spec and framework files + +import 'zone.js/dist/zone-testing'; +import { getTestBed } from '@angular/core/testing'; +import { + BrowserDynamicTestingModule, + platformBrowserDynamicTesting +} from '@angular/platform-browser-dynamic/testing'; + +declare const require: { + context(path: string, deep?: boolean, filter?: RegExp): { + keys(): string[]; + (id: string): T; + }; +}; + +// First, initialize the Angular testing environment. +getTestBed().initTestEnvironment( + BrowserDynamicTestingModule, + platformBrowserDynamicTesting() +); +// Then we find all the tests. +const context = require.context('./', true, /\.spec\.ts$/); +// And load the modules. +context.keys().map(context); diff --git a/examples/angular/with-passwordless/ui/tsconfig.app.json b/examples/angular/with-passwordless/ui/tsconfig.app.json new file mode 100644 index 00000000..82d91dc4 --- /dev/null +++ b/examples/angular/with-passwordless/ui/tsconfig.app.json @@ -0,0 +1,15 @@ +/* To learn more about this file see: https://angular.io/config/tsconfig. */ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "./out-tsc/app", + "types": [] + }, + "files": [ + "src/main.ts", + "src/polyfills.ts" + ], + "include": [ + "src/**/*.d.ts" + ] +} diff --git a/examples/angular/with-passwordless/ui/tsconfig.json b/examples/angular/with-passwordless/ui/tsconfig.json new file mode 100644 index 00000000..4a4dc628 --- /dev/null +++ b/examples/angular/with-passwordless/ui/tsconfig.json @@ -0,0 +1,23 @@ +/* To learn more about this file see: https://angular.io/config/tsconfig. */ +{ + "compileOnSave": false, + "compilerOptions": { + "baseUrl": "./", + "outDir": "./dist/out-tsc", + "sourceMap": true, + "declaration": false, + "downlevelIteration": true, + "experimentalDecorators": true, + "moduleResolution": "node", + "importHelpers": true, + "target": "es2015", + "module": "es2020", + "lib": [ + "es2018", + "dom" + ] + }, + "angularCompilerOptions": { + "enableI18nLegacyMessageIdFormat": false + } +} diff --git a/examples/angular/with-passwordless/ui/tsconfig.spec.json b/examples/angular/with-passwordless/ui/tsconfig.spec.json new file mode 100644 index 00000000..092345b0 --- /dev/null +++ b/examples/angular/with-passwordless/ui/tsconfig.spec.json @@ -0,0 +1,18 @@ +/* To learn more about this file see: https://angular.io/config/tsconfig. */ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "./out-tsc/spec", + "types": [ + "jasmine" + ] + }, + "files": [ + "src/test.ts", + "src/polyfills.ts" + ], + "include": [ + "src/**/*.spec.ts", + "src/**/*.d.ts" + ] +} diff --git a/examples/angular/with-passwordless/ui/tslint.json b/examples/angular/with-passwordless/ui/tslint.json new file mode 100644 index 00000000..277c8eba --- /dev/null +++ b/examples/angular/with-passwordless/ui/tslint.json @@ -0,0 +1,152 @@ +{ + "extends": "tslint:recommended", + "rulesDirectory": [ + "codelyzer" + ], + "rules": { + "align": { + "options": [ + "parameters", + "statements" + ] + }, + "array-type": false, + "arrow-return-shorthand": true, + "curly": true, + "deprecation": { + "severity": "warning" + }, + "eofline": true, + "import-blacklist": [ + true, + "rxjs/Rx" + ], + "import-spacing": true, + "indent": { + "options": [ + "spaces" + ] + }, + "max-classes-per-file": false, + "max-line-length": [ + true, + 140 + ], + "member-ordering": [ + true, + { + "order": [ + "static-field", + "instance-field", + "static-method", + "instance-method" + ] + } + ], + "no-console": [ + true, + "debug", + "info", + "time", + "timeEnd", + "trace" + ], + "no-empty": false, + "no-inferrable-types": [ + true, + "ignore-params" + ], + "no-non-null-assertion": true, + "no-redundant-jsdoc": true, + "no-switch-case-fall-through": true, + "no-var-requires": false, + "object-literal-key-quotes": [ + true, + "as-needed" + ], + "quotemark": [ + true, + "single" + ], + "semicolon": { + "options": [ + "always" + ] + }, + "space-before-function-paren": { + "options": { + "anonymous": "never", + "asyncArrow": "always", + "constructor": "never", + "method": "never", + "named": "never" + } + }, + "typedef": [ + true, + "call-signature" + ], + "typedef-whitespace": { + "options": [ + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + }, + { + "call-signature": "onespace", + "index-signature": "onespace", + "parameter": "onespace", + "property-declaration": "onespace", + "variable-declaration": "onespace" + } + ] + }, + "variable-name": { + "options": [ + "ban-keywords", + "check-format", + "allow-pascal-case" + ] + }, + "whitespace": { + "options": [ + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type", + "check-typecast" + ] + }, + "component-class-suffix": true, + "contextual-lifecycle": true, + "directive-class-suffix": true, + "no-conflicting-lifecycle": true, + "no-host-metadata-property": true, + "no-input-rename": true, + "no-inputs-metadata-property": true, + "no-output-native": true, + "no-output-on-prefix": true, + "no-output-rename": true, + "no-outputs-metadata-property": true, + "template-banana-in-box": true, + "template-no-negated-async": true, + "use-lifecycle-interface": true, + "use-pipe-transform-interface": true, + "directive-selector": [ + true, + "attribute", + "app", + "camelCase" + ], + "component-selector": [ + true, + "element", + "app", + "kebab-case" + ] + } +}