Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Login extends AppCompatActivity {
- TextView loginButton;
- EditText loginUserName, loginPassword;
- private Snackbar snackbar;
- private ProgressDialog pd;
- private TextInputLayout mTiEmail;
- private TextInputLayout mTiPassword;
- private CompositeSubscription mSubscriptions;
- private SharedPreferences mSharedPreferences;
- private Boolean loggedIn = false;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_login);
- mSubscriptions = new CompositeSubscription();
- mSubscriptions = new CompositeSubscription();
- loginUserName = (EditText) findViewById(R.id.email_edit);
- loginPassword = (EditText) findViewById(R.id.pass_edit);
- pd = new ProgressDialog(Login.this);
- mTiEmail = (TextInputLayout) findViewById(R.id.email1);
- mTiPassword = (TextInputLayout) findViewById(R.id.password);
- loginButton = (
- TextView)findViewById(R.id.btn_login);
- initSharedPreferences();
- loginButton.setOnClickListener(view -> login());
- }
- @Override
- protected void onResume() {
- super.onResume();
- //In onresume fetching value from sharedpreference
- mSharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
- if(mSharedPreferences.getBoolean("LoggedIn", false)){
- Intent intent = new Intent(Login.this,Dashboard.class);
- startActivity(intent);
- } else {
- loginButton.setOnClickListener(view -> login());
- //Do other stuff
- }
- }
- private void initSharedPreferences() {
- mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(Login.this);
- }
- private void login() {
- String username = loginUserName.getText().toString();
- String password = loginPassword.getText().toString();
- loginProcess(username,password);
- /*if (!validateEmail(email)) {
- err++;
- mTiEmail.setError("Email should be valid !");
- }
- if (!validateFields(password)) {
- err++;
- mTiPassword.setError("Password should not be empty !");
- }*/
- }
- private void loginProcess(String username, String password) {
- mSubscriptions.add(NetworkUtil.getRetrofit(username,password).login()
- .observeOn(AndroidSchedulers.mainThread())
- .subscribeOn(Schedulers.io())
- .subscribe(this::handleResponse,this::handleError));
- }
- private void handleResponse(User response) {
- SharedPreferences.Editor editor = mSharedPreferences.edit();
- editor.putString(Constants.USERNAME,response.getUsername());
- editor.putBoolean("LoggedIn", true);
- editor.apply();
- loginUserName.setText(null);
- loginPassword.setText(null);
- Intent in = new Intent(Login.this,Dashboard.class);
- startActivity(in);
- Toast.makeText(this, "REGISTERED-->>", Toast.LENGTH_LONG).show();
- }
- private void handleError(Throwable error) {
- if (error instanceof HttpException) {
- Gson gson = new GsonBuilder().create();
- try {
- String errorBody = ((HttpException) error).response().errorBody().string();
- Response response = gson.fromJson(errorBody,Response.class);
- Toast.makeText(this,response.getMessage(), Toast.LENGTH_LONG).show();
- } catch (IOException e) {
- e.printStackTrace();
- }
- } else {
- Toast.makeText(this, error.getMessage(), Toast.LENGTH_SHORT).show();
- }
- }
- }
- public interface RetrofitInterface {
- @POST("users")
- Observable<Response> register(@Body User user);
- @POST("logins")
- Observable<Response> login();
- @GET("users/{email}")
- Observable<User> getProfile(@Path("email") String email);
- @PUT("users/{email}")
- Observable<Response> changePassword(@Path("email") String email, @Body User user);
- @POST("users/{email}/password")
- Observable<Response> resetPasswordInit(@Path("email") String email);
- @POST("users/{email}/password")
- Observable<Response> resetPasswordFinish(@Path("email") String email, @Body User user);
- }
- public class User {
- private String name;
- private String username;
- private String password;
- private String created_at;
- private String newPassword;
- private String token;
- public void setName(String name) {
- this.name = name;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getName() {
- return name;
- }
- public String getUsername() {
- return username;
- }
- public String getPassword() {
- return password;
- }
- public String getCreated_at() {
- return created_at;
- }
- public void setNewPassword(String newPassword) {
- this.newPassword = newPassword;
- }
- public void setToken(String token) {
- this.token = token;
- }
- }
- public class Response {
- private String message;
- private String token;
- public String getMessage() {
- return message;
- }
- public String getToken() {
- return token;
- }
- }
- public class Constants {
- public static final String BASE_URL = "http://192.168.2.145:8083/api/users/";
- public static final String TOKEN = "token";
- public static final String USERNAME = "username";
- //This would be the name of our shared preferences
- public static final String SHARED_PREF_NAME = "myloginapp";
- //This would be used to store the email of current logged in user
- public static final String EMAIL_SHARED_PREF = "email";
- //We will use this to store the boolean in sharedpreference to track user is loggedin or not
- public static final String LOGGEDIN_SHARED_PREF = "loggedin";
- }
- const User= require("../model/user.model.js");
- const { initSession} = require('../utils/utils');
- const logins = (req,res,next)=> {
- console.log("login user::"+JSON.stringify(req.body));
- User.findOne({ username : req.body.username }, function(err, user) {
- if (!user) {
- return res.status(404).send({
- message : "User not found."
- });
- }
- else {
- if (user.validPassword(req.body.password)) {
- const sess = initSession(user._id);
- res
- .cookie('token', sess.token, {
- httpOnly: true,
- sameSite: true,
- maxAge: 2 * 60 * 60 * 1000
- })
- .json({
- title: 'Login Successful',
- detail: 'Successfully validated user credentials',
- csrfToken: sess.csrfToken,
- });
- }
- else {
- return res.status(400).send({
- message : "Wrong Password"
- });
- }
- }
- })
- }
- module.exports = { logins };
- module.exports = function(app) {
- var express = require("express");
- const path = require("path");
- const Register=require('../controllers/register.controller');
- const Login=require('../controllers/login.controller');
- var router = express.Router();
- router.use(function (req,res,next) {
- console.log("/" + req.method);
- next();
- });
- app.get('/', (req, res) => res.end('Welcome to Learn2Crack !'));
- //post Register details
- app.post('/api/users/register',Register.save);
- //fetch Register details
- app.get('/api/users/fetchregister',Register.fetch);
- //logging in a user
- app.post('/api/users/logins', Login.logins);
- }
Add Comment
Please, Sign In to add comment