Skip to content
blog.fossasia.org
  • Home
  • Projects
    • Contribute
  • Events
    • Eventyay Platform
    • Event Sponsorships
    • Event Calendar
    • FOSSASIA Summit
    • OpenTechSummit China
    • OpenTechSummit Thailand
    • OpenTechSummit Vietnam
    • Jugaad Fest India
    • Past Events
      • FOSSASIA Summit 2022
      • FOSSASIA Summit 2021
      • FOSSASIA Summit 2020
      • FOSSASIA Summit 2019
      • FOSSASIA Summit 2018
      • FOSSASIA Summit 2017
      • FOSSASIA Summit 2016
      • FOSSASIA Summit 2015
      • FOSSASIA Summit 2014
      • FOSSASIA Summit 2012
      • FOSSASIA Summit 2011
      • FOSSASIA Summit 2010
      • GNOME.Asia 2009
      • MiniDebConf Vietnam 2010
      • Sciencehack.Asia
      • Science Hack India
  • Programs
    • Programs and Opportunities
    • Jobs Opportunities
    • Program Guidelines
    • Codeheat Contest
    • University Internship Program
    • University Student Coding Programs
    • High School Student Program
    • Advanced Developer Program
    • Become a Mentor
      • Become A University Student Mentor
      • Become A High School Student Mentor
  • Shop
  • Blog
  • About
    • Jobs
    • Membership
    • Activities
    • Background & Mission
    • Best Practices
    • Licenses
    • Team
    • Code of Conduct
  • Donate
Menu Close
  • Home
  • Projects
    • Contribute
  • Events
    • Eventyay Platform
    • Event Sponsorships
    • Event Calendar
    • FOSSASIA Summit
    • OpenTechSummit China
    • OpenTechSummit Thailand
    • OpenTechSummit Vietnam
    • Jugaad Fest India
    • Past Events
      • FOSSASIA Summit 2022
      • FOSSASIA Summit 2021
      • FOSSASIA Summit 2020
      • FOSSASIA Summit 2019
      • FOSSASIA Summit 2018
      • FOSSASIA Summit 2017
      • FOSSASIA Summit 2016
      • FOSSASIA Summit 2015
      • FOSSASIA Summit 2014
      • FOSSASIA Summit 2012
      • FOSSASIA Summit 2011
      • FOSSASIA Summit 2010
      • GNOME.Asia 2009
      • MiniDebConf Vietnam 2010
      • Sciencehack.Asia
      • Science Hack India
  • Programs
    • Programs and Opportunities
    • Jobs Opportunities
    • Program Guidelines
    • Codeheat Contest
    • University Internship Program
    • University Student Coding Programs
    • High School Student Program
    • Advanced Developer Program
    • Become a Mentor
      • Become A University Student Mentor
      • Become A High School Student Mentor
  • Shop
  • Blog
  • About
    • Jobs
    • Membership
    • Activities
    • Background & Mission
    • Best Practices
    • Licenses
    • Team
    • Code of Conduct
  • Donate

Signup

Read more about the article Configuring Firebase in Loklak Search

Configuring Firebase in Loklak Search

  • Post author:simsausaurabh
  • Post published:July 6, 2018
  • Post category:FOSSASIA/GSoC/loklak
  • Post comments:0 Comments

In process of expanding features of loklak to provide support of twitter api to the users, it was a good idea to go with Firebase as the managing medium for logged in or authenticated users. After integration of Firebase into loklak, users will be able to authenticate themselves securely with Facebook, Google, and Twitter and get access to the results from Twitter api on loklak. In this blog post, I will be discussing the Firebase configuration process into loklak.

Setting up Firebase environment configuration

Without explicitly going into each single detail of the integration process which is already provided by Firebase and other mediums, I will jump on to the main key characteristics of configuring Firebase into Loklak. This step covers the configuration of Firebase environment parameters. Goto Firebase console and copy the project’s environment’s parameters for web app option and paste it into environments/environment.ts file inside the project as given below by replacing all ‘*’ with the required values.

export const environment = {
    production: true,
    firebase: {
    apiKey: ‘***’,
    authDomain: ‘***’,
    databaseURL: ‘***’,
    projectId: ‘***’,
    storageBucket: ‘***’,
    messagingSenderId: ‘***’
    }
};

Initialise the Firebase app

Next step would be to cover establish the Firebase app in app.module.ts by importing necessary packages as given below.

import { AngularFireModule } from ‘angularfire2’;
import { AngularFirestoreModule } from ‘angularfire2/firestore’;
import { AngularFireAuthModule } from ‘angularfire2/auth’;
import { environment } from ‘../environments/environment’; 

...
imports: [
  …
  AngularFireModule.initializeApp(environment.firebase,
    ‘loklak-search’),
  AngularFirestoreModule,
  AngularFireAuthModule
]

Creating Auth service with various Auth providers

This is the main part of the Firebase configuration. Create a new Auth service in ‘services/’, and include the given below methods for providing authentication using – Twitter, Facebook, Google, and Email & Password. We will also provide logout feature for the user to log out from the current service provider. Given below is an example of adding Google as the service provider for authentication, it can be similarly used to provider authentication for other providers.

import { Injectable } from ‘@angular/core’;
import { AngularFireAuth } from ‘angularfire2/auth’;
import { Observable } from ‘rxjs’;
import * as firebase from ‘firebase/app’;

@Injectable()
export class AuthService {

    public authState: Observable<firebase.User>;
    constructor( private afAuth: AngularFireAuth ) {
        this.authState = this.afAuth.authState;
    }

    signInWithGoogle() {
        return this.afAuth.auth.signInWithPopup(
            new firebase.auth.GoogleAuthProvider()
        );
    }

    logout() {
        this.afAuth.auth.signOut();
    }
}

 

We are using AngularFireAuth to provide authentication for every provider.

Using Auth service in the required component

This step would cover up the last portion to use the auth service to actually provide authenticated login. Now, import the created auth service and other packages and create a property of auth service and a user variable to keep check on the current user status (We would store the current status on the constructor call).

import { AuthService } 
    from ‘./../services/auth.service’;
import * as firebase from ‘firebase/app’;
…
public user: Observable<firebase.User>;
    constructor(
        private _eref: ElementRef,
        private afAuth: AuthService
    ) {
        this.user = this.afAuth.authState;
    }

 

Now, call the methods of auth service and storing the status of current user in the user property created above (For an example, calling only twitter auth and logout method).

signInWithTwitter() {
    this.afAuth.signInWithTwitter();
}
logout() {
    this.afAuth.logout();
}

 

These methods could now be easily called inside (click) property of any appropriate html div/tag to provide login or logout feature.

Testing Auth Login

Click on the div/tag which is calling the SignIn methods and look onto the console for results.

Resources

  • Firebase: Getting Started
  • Firebase: Firebase Authentication Providers
  • ITNEXT: Firebase Authentication
Continue ReadingConfiguring Firebase in Loklak Search
Read more about the article Implementation of SUSI.AI Signup Service

Implementation of SUSI.AI Signup Service

  • Post author:DravitLochan
  • Post published:August 27, 2017
  • Post category:API/FOSSASIA/GSoC/SUSI.AI
  • Post comments:0 Comments

In this blog, I discuss the complete implementation of SUSI server when a user signs up with SUSI. Since public signup is enabled, minimal user role to access the servlet is ANONYMOUS. Given below is the API endpoint at which a signup request has to be made.

http://api.susi.ai/aaa/signup.json

Here we do not have much options unlike Login service. . Requests can be made in following ways with different parameters:

http://api.susi.ai/aaa/signup.json?signup=test@fossasia.com&password=Rest@123

http://api.susi.ai/aaa/signup.json?getParameters=true

http://api.susi.ai/aaa/signup.json?access_token={30 characters long access token}&validateEmail=test@fossasia.com&request_session=true

First one is the request which client makes, asking the server to register the user with email id test@fossasia.com and password as Reset@123. On receiving a request which has parameters signup and password, server looks back in the database and verifies that a user with same email id exists or not. If email id already exists, server throws an error stating “email already taken”. Given below is a small code snippet for better understanding.

ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login, signup);
		Authentication authentication = DAO.getAuthentication(credential);

		if (authentication.getIdentity() != null) {
			throw new APIException(422, "email already taken");
		}

If client is not found in the database, a new identity is generated for the user and is set in authentication.json file. Next, a random salt string is generated which acts as salt to hash the user’s password. Since the same salt will be required at the time of matching the password for validation, we store both the salt and password hash in authentication.json file.

Now, if the database is going to encounter it’s first user, Automatically,  BUREAUCRAT (Role with maximum power) will be assigned as his/her user role. To do this, we first get a list of all the users with the help of DAO class and count number of users present in it. Take a look at the code given below,

Authorization authorization = DAO.getAuthorization(identity);
		Collection<ClientIdentity> authorized = DAO.getAuthorizedClients();
		List<String> keysList = new ArrayList<String>();
		authorized.forEach(client -> keysList.add(client.toString()));
		String[] keysArray = keysList.toArray(new String[keysList.size()]);
		if(keysArray.length == 1) {
			authorization.setUserRole(UserRole.BUREAUCRAT);
		} else {
			authorization.setUserRole(UserRole.USER);
		}

In  further steps, a random token is generated and marked as the verification token for the user who just signed-up. Other attributes for the token are also set like expiry time. Finally, account verification mail’s template is picked from “conf/templates/verification-mail” file and used as the body for the user verification email.

The second type of request is quite simple which is just to request a regular expression from the server to give proper information to the user. It’s code is quite easy and self understandable.

Third type of request is sent to the server when user clicks on the link received in the account verification email. Taking a closer look at the account verification link, one could easily decode that the request would be redirected to /aaa/signup.json with parameters

  • Access_token     :          30 characters long access token
  • validateEmail    :          user’s email id
  • request_session :         true

Access_token makes up the unique id for the user. ValidateEmail is to make it easier for server to generate a client identity. Let us now understand how server picks up each parameter and activates the user’s account.

if (post.get("validateEmail", null) != null) {
			if((auth.getIdentity().getName().equals(post.get("validateEmail", null)) && auth.getIdentity().isEmail()) // the user is logged in via an access token from the email {

				ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login,
						auth.getIdentity().getName());
Authentication authentication =     DAO.getAuthentication(credential);

				if (authentication.getIdentity() == null) {
					authentication.delete();
					throw new APIException(400, "Bad request");
				}
				authentication.put("activated", true);
				result.put("accepted", true);
result.put("message", "You successfully verified your                                        account!");
				return new ServiceResponse(result);
			}
			throw new APIException(400, "Bad request"); // do not leak if user exists or not
		}

In the above code snippet, an object of ClientCredential class is generated and used to get authentication object for the user. If user is not found (name in authentication object is null), server throws error with error message “Bad Request”. Finally, If no error was encountered, server activates the user.

In getDefaultPermissions() function, permission for each user role is specified. All the users registered are allowed to register other users, but no user with anonymous user role can register anyone else except him/her.

Resources

  • Post by Tutorials Point on How to send email in JAVA
  • Post by Wikipedia on What is DAO?
  • Answer by Tomasz Nurkiewicz on StackoverFlow Need for server side account validation instead of client side

 

Continue ReadingImplementation of SUSI.AI Signup Service
Read more about the article SUSI Account Verification – From JSON to Accounts

SUSI Account Verification – From JSON to Accounts

  • Post author:DravitLochan
  • Post published:August 27, 2017
  • Post category:FOSSASIA/GSoC/SUSI.AI
  • Post comments:0 Comments

In this blog post, I’ll be telling on how SUSI-server synchronizes with SUSI accounts front-end and enable users to have a SUSI verified account. Apart from how server processes the query and responds to it, I also discuss the role of SUSI accounts as a client in it.

Beginning with server, at the time of signup, a mail is sent to user’s email id {only is user is not already registered}. This email contains a link, clicking on which a request is sent to server to check if the combination of email id and the access_token  passed matches or not. Let us quickly look at the email and decode it.

http://accounts.susi.ai/verify-account?access_token=hU86imBzXP3hcLgBgN6x4ShLuDopyH&validateEmail=dlochangupta@gmail.com&request_session=true

As you can see, the base URL is http://accounts.susi.ai and the route to which the user is redirected ‘/verify-account’. What does the rest of the parameters do?

  • access _token —> access token
  • validateEmail —> email id of the user
  • request_session —> boolean value to request a session

access_token contains a key which will be valid for 7 days (i.e. 604800 seconds) since the account was registered.

Since signing up and verifying user’s account, both share Signup.java servlet, As a first step, server checks if the request contains ‘validateEmail’ in the parameter list. If yes, AND it is not a null parameter, server is sure that it is a account verification request. Next it proceeds with checking if user has even registered or not. If not, user is notified with error code 400 and error message “Bad request”. Otherwise, by now server has found the client ID already and only steps left are to make “activated” attribute set to true. Once done successfully, server responds with a similar type of JSON response :

{
  "accepted": true,
  "message": "You successfully verified your account!",
  "session": {"identity": {
    "type": "email",
    "name": "test@fossasia.com",
    "anonymous": false
  }}
}

But you did not come across a similar type of JSON response. Did you? Here comes the role of client. If you replace http://accounts.susi.ai/verify-account with http://api.susi.ai/aaa/signup.json in the link you received, you will indeed find this JSON response. Since a user is redirected to http://accounts.susi.ai/verify-account with above mentioned 3 parameters, in componentDidMount() function, list of these parameters is extracted from component props.

componentDidMount() {
    const {
      accessToken, validateEmail, requestSession
    } = this.props;

This list was declared and initialized with some values initially so that if these are not found in the parameter list, client would be able to figure it out.

const urlPropsQueryConfig = {
  accessToken: { type: UrlQueryParamTypes.string, queryParam: 'access_token' },
  requessession: { type: UrlQueryParamTypes.string},
  validateEmail: { type: UrlQueryParamTypes.string },
};

static defaultProps = {
    token: 'null',
    validateEmail: 'null',
    requestSession: false,
  }

Additional Resources

  1. Site: npmjs.com on How to extract url query parameters from a link? (official documentation)
  2. Site: daveceddia.com on How to make an AJAX call in ReactJS. Blog post by Dave Ceddia
Continue ReadingSUSI Account Verification – From JSON to Accounts
  • FOSSASIA
  • Blog
  • GitHub
  • Projects
  • Code of Conduct
  • About
  • Contact
Copyright - OceanWP Theme by OceanWP