Skip to content
This repository has been archived by the owner on Jul 30, 2021. It is now read-only.

Commit

Permalink
mobile auth integration (#285)
Browse files Browse the repository at this point in the history
  • Loading branch information
puncsky committed Jan 31, 2020
1 parent bf436fc commit 16e419e
Show file tree
Hide file tree
Showing 11 changed files with 79 additions and 62 deletions.
1 change: 0 additions & 1 deletion .env.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,3 @@ MONGODB_URI=TODO
AUTH_SECRET=SECRET
FULLCONTACT_API_KEY=TODO
MAILGUN_API_KEY=TODO
ENABLE_GUANXI_DAILY=false
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@
"webpack-manifest-plugin": "2.2.0"
},
"dependencies": {
"@ag-grid-community/all-modules": "22.1.1",
"@ag-grid-community/react": "22.1.2",
"@axetroy/react-github-calendar": "2.0.0",
"@babel/cli": "7.8.4",
"@babel/core": "7.8.4",
Expand Down Expand Up @@ -132,8 +134,6 @@
"@types/styletron-react": "5.0.2",
"@types/uuid": "3.4.7",
"@types/validator": "10.11.3",
"@ag-grid-community/all-modules": "22.1.1",
"@ag-grid-community/react": "22.1.2",
"antd": "3.26.7",
"apollo-cache-inmemory": "1.6.5",
"apollo-client": "2.6.8",
Expand Down
7 changes: 7 additions & 0 deletions src/api-gateway/api-gateway.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,9 @@ type Mutation {
type Query {
# get the article
articles(id: String): [ArticleResponse!]

# get the user
userProfile(userId: String!): UserProfileResponse
interactions(
contactId: String
isSelf: Boolean
Expand Down Expand Up @@ -248,3 +251,7 @@ input UpsertInteraction {
relatedHumans: [String!]!
public: Boolean
}

type UserProfileResponse {
email: String!
}
30 changes: 4 additions & 26 deletions src/api-gateway/api-gateway.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
import { HttpLink } from "apollo-link-http";
import {
ApolloServer,
introspectSchema,
makeRemoteExecutableSchema,
mergeSchemas
} from "apollo-server-koa";
import { ApolloServer, mergeSchemas } from "apollo-server-koa";
import koa from "koa";
import { logger } from "onefx/lib/integrated-gateways/logger";
import path from "path";
import "reflect-metadata";
import { buildSchema } from "type-graphql";
Expand All @@ -15,6 +8,7 @@ import { Gateways } from "../server/gateway/gateway";
import { MyServer } from "../server/start-server";
import { ArticleResolver } from "../shared/article/article-resolver";
import { OnefxAuth } from "../shared/onefx-auth";
import { customAuthChecker } from "./auth-checker";
import { AccountResolver } from "./resolvers/account-resolver";
import { ContactResolver } from "./resolvers/contact-resolver";
import { MetaResolver } from "./resolvers/meta-resolver";
Expand Down Expand Up @@ -45,26 +39,10 @@ export async function setApiGateway(server: MyServer): Promise<void> {
path: sdlPath,
commentDescriptions: true
},
validate: false
validate: false,
authChecker: customAuthChecker
});
const schemas = [localSchema];

if (process.env.ENABLE_GUANXI_DAILY) {
try {
const remoteLink = new HttpLink({
uri: `https://tianpan.co/api-gateway/`,
fetch
});
const remoteSchema = makeRemoteExecutableSchema({
schema: await introspectSchema(remoteLink),
link: remoteLink
});
schemas.push(remoteSchema);
} catch (err) {
logger.error(`failed to link external tianpan.co api`);
}
}

const schema = mergeSchemas({
schemas
});
Expand Down
9 changes: 9 additions & 0 deletions src/api-gateway/auth-checker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Context } from "./api-gateway";

export const customAuthChecker = ({ context }: { context: Context }) => {
const { userId } = context;
if (!userId) {
throw new Error("Access denied! Please login to continue!");
}
return true; // or false if access is denied
};
12 changes: 0 additions & 12 deletions src/api-gateway/context.ts

This file was deleted.

39 changes: 38 additions & 1 deletion src/api-gateway/resolvers/account-resolver.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { AuthenticationError } from "apollo-server-errors";
import { Arg, Ctx, Field, InputType, Mutation } from "type-graphql";
import {
Arg,
Args,
ArgsType,
Authorized,
Ctx,
Field,
InputType,
Mutation,
ObjectType,
Query
} from "type-graphql";

import { Context } from "../api-gateway";

Expand All @@ -9,6 +20,18 @@ class DeleteAccountInput {
email: string;
}

@ArgsType()
class UserProfileRequest {
@Field(_ => String)
userId: string;
}

@ObjectType()
class UserProfileResponse {
@Field(_ => String)
email: string;
}

export class AccountResolver {
@Mutation(_ => Boolean)
public async deleteAccount(
Expand Down Expand Up @@ -38,4 +61,18 @@ export class AccountResolver {
return Boolean(false);
}
}

@Authorized()
@Query(_ => UserProfileResponse, {
description: "get the user",
nullable: true
})
public async userProfile(
@Args()
args: UserProfileRequest,
@Ctx()
ctx: Context
): Promise<UserProfileResponse | null> {
return ctx.auth.user.getById(args.userId);
}
}
4 changes: 2 additions & 2 deletions src/shared/article/article-resolver.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Args, Ctx, Query, Resolver } from "type-graphql";
import { IContext } from "../../api-gateway/context";
import { Context } from "../../api-gateway/api-gateway";
import { ArticleService } from "./article-service";
import { ArticleResponse, ArticlesRequest } from "./article-types";

Expand All @@ -19,7 +19,7 @@ export class ArticleResolver {
@Args()
args: ArticlesRequest,
@Ctx()
_: IContext
_: Context
): Promise<Array<ArticleResponse>> {
const article = this.articleService.getPostById(args.id);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { combineReducers } from "redux";
import validator from "validator";
import { MyServer } from "../../../server/start-server";
import { MyContext } from "../../../types/global";
import { TUser } from "../../onefx-auth/model/user-model";
import { TUserDoc } from "../../onefx-auth/model/user-model";
import { IdentityAppContainer } from "./view/identity-app-container";

const PASSWORD_MIN_LENGTH = 6;
Expand Down Expand Up @@ -52,7 +52,7 @@ export function passwordValidator(): Handler {

function isMobileWebView(ctx: MyContext): boolean {
const isMobile =
ctx.headers["x-app-id"] === "mobile-rebinder" ||
ctx.headers["x-app-id"] === "mobile-guanxi-io" ||
ctx.session.isMobileWebView;
if (isMobile) {
ctx.session.isMobileWebView = true;
Expand Down Expand Up @@ -131,7 +131,7 @@ export function setEmailPasswordIdentityProviderRoutes(server: MyServer): void {
async (ctx: MyContext, next: Function) => {
const { email, password } = ctx.request.body;
try {
const user: TUser = await server.auth.user.newAndSave({
const user: TUserDoc = await server.auth.user.newAndSave({
email,
password,
ip: ctx.headers["x-forward-for"]
Expand Down
5 changes: 1 addition & 4 deletions src/shared/onefx-auth/auth-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,7 @@ export type AuthConfig = {
export const authConfig = {
cookieName: "auth",
cookieOpts: {
domain:
String(process.env.NODE_ENV).indexOf("production") === -1
? "localhost"
: "guanxilab.com",
domain: "",

secure: false,
httpOnly: true,
Expand Down
24 changes: 13 additions & 11 deletions src/shared/onefx-auth/model/user-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,21 @@ type TNewUser = {
ip: string;
};

export type TUser = mongoose.Document &
TNewUser & {
avatar: string;
type TUser = TNewUser & {
id: string;
avatar: string;

isBlocked: boolean;
lifetimeHumanId: string;
isBlocked: boolean;
lifetimeHumanId: string;

createAt: Date;
updateAt: Date;
};
createAt: Date;
updateAt: Date;
};

export type TUserDoc = mongoose.Document & TUser;

export class UserModel {
public Model: mongoose.Model<TUser>;
public Model: mongoose.Model<TUserDoc>;

constructor({ mongoose }: { mongoose: mongoose.Mongoose }) {
const UserSchema = new Schema({
Expand Down Expand Up @@ -96,14 +98,14 @@ export class UserModel {
public async updateAssocProfileId(
userId: string,
lifetimeHumanId: string
): Promise<TUser> {
): Promise<TUserDoc> {
return this.Model.update({ _id: userId }, { lifetimeHumanId });
}

public async updatePassword(
userId: string,
password: string
): Promise<TUser | null> {
): Promise<TUserDoc | null> {
return this.Model.update(
{ _id: userId },
{ password: await tools.bhash(password) }
Expand Down

0 comments on commit 16e419e

Please sign in to comment.