Guest User

Untitled

a guest
Oct 16th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.12 KB | None | 0 0
  1. public class Login extends AppCompatActivity {
  2. TextView loginButton;
  3. EditText loginUserName, loginPassword;
  4.  
  5. private Snackbar snackbar;
  6. private ProgressDialog pd;
  7. private TextInputLayout mTiEmail;
  8. private TextInputLayout mTiPassword;
  9. private CompositeSubscription mSubscriptions;
  10. private SharedPreferences mSharedPreferences;
  11. private Boolean loggedIn = false;
  12. @Override
  13. protected void onCreate(Bundle savedInstanceState) {
  14. super.onCreate(savedInstanceState);
  15. setContentView(R.layout.activity_login);
  16.  
  17. mSubscriptions = new CompositeSubscription();
  18. mSubscriptions = new CompositeSubscription();
  19.  
  20. loginUserName = (EditText) findViewById(R.id.email_edit);
  21. loginPassword = (EditText) findViewById(R.id.pass_edit);
  22. pd = new ProgressDialog(Login.this);
  23. mTiEmail = (TextInputLayout) findViewById(R.id.email1);
  24. mTiPassword = (TextInputLayout) findViewById(R.id.password);
  25. loginButton = (
  26. TextView)findViewById(R.id.btn_login);
  27. initSharedPreferences();
  28. loginButton.setOnClickListener(view -> login());
  29.  
  30. }
  31. @Override
  32. protected void onResume() {
  33. super.onResume();
  34. //In onresume fetching value from sharedpreference
  35. mSharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
  36. if(mSharedPreferences.getBoolean("LoggedIn", false)){
  37. Intent intent = new Intent(Login.this,Dashboard.class);
  38. startActivity(intent);
  39. } else {
  40. loginButton.setOnClickListener(view -> login());
  41.  
  42. //Do other stuff
  43. }
  44. }
  45. private void initSharedPreferences() {
  46.  
  47. mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(Login.this);
  48. }
  49. private void login() {
  50.  
  51.  
  52.  
  53. String username = loginUserName.getText().toString();
  54. String password = loginPassword.getText().toString();
  55.  
  56. loginProcess(username,password);
  57.  
  58.  
  59. /*if (!validateEmail(email)) {
  60.  
  61. err++;
  62. mTiEmail.setError("Email should be valid !");
  63. }
  64.  
  65. if (!validateFields(password)) {
  66.  
  67. err++;
  68. mTiPassword.setError("Password should not be empty !");
  69. }*/
  70.  
  71.  
  72. }
  73.  
  74. private void loginProcess(String username, String password) {
  75.  
  76. mSubscriptions.add(NetworkUtil.getRetrofit(username,password).login()
  77. .observeOn(AndroidSchedulers.mainThread())
  78. .subscribeOn(Schedulers.io())
  79. .subscribe(this::handleResponse,this::handleError));
  80. }
  81. private void handleResponse(User response) {
  82.  
  83. SharedPreferences.Editor editor = mSharedPreferences.edit();
  84. editor.putString(Constants.USERNAME,response.getUsername());
  85. editor.putBoolean("LoggedIn", true);
  86. editor.apply();
  87.  
  88. loginUserName.setText(null);
  89. loginPassword.setText(null);
  90. Intent in = new Intent(Login.this,Dashboard.class);
  91. startActivity(in);
  92. Toast.makeText(this, "REGISTERED-->>", Toast.LENGTH_LONG).show();
  93. }
  94. private void handleError(Throwable error) {
  95.  
  96.  
  97. if (error instanceof HttpException) {
  98.  
  99. Gson gson = new GsonBuilder().create();
  100.  
  101. try {
  102. String errorBody = ((HttpException) error).response().errorBody().string();
  103. Response response = gson.fromJson(errorBody,Response.class);
  104. Toast.makeText(this,response.getMessage(), Toast.LENGTH_LONG).show();
  105.  
  106. } catch (IOException e) {
  107. e.printStackTrace();
  108. }
  109. } else {
  110.  
  111. Toast.makeText(this, error.getMessage(), Toast.LENGTH_SHORT).show();
  112. }
  113. }
  114.  
  115.  
  116. }
  117.  
  118. public interface RetrofitInterface {
  119.  
  120. @POST("users")
  121. Observable<Response> register(@Body User user);
  122.  
  123. @POST("logins")
  124. Observable<Response> login();
  125.  
  126. @GET("users/{email}")
  127. Observable<User> getProfile(@Path("email") String email);
  128.  
  129. @PUT("users/{email}")
  130. Observable<Response> changePassword(@Path("email") String email, @Body User user);
  131.  
  132. @POST("users/{email}/password")
  133. Observable<Response> resetPasswordInit(@Path("email") String email);
  134.  
  135. @POST("users/{email}/password")
  136. Observable<Response> resetPasswordFinish(@Path("email") String email, @Body User user);
  137. }
  138.  
  139. public class User {
  140.  
  141. private String name;
  142. private String username;
  143. private String password;
  144. private String created_at;
  145. private String newPassword;
  146. private String token;
  147.  
  148. public void setName(String name) {
  149. this.name = name;
  150. }
  151.  
  152. public void setUsername(String username) {
  153. this.username = username;
  154. }
  155.  
  156. public void setPassword(String password) {
  157. this.password = password;
  158. }
  159.  
  160. public String getName() {
  161. return name;
  162. }
  163.  
  164. public String getUsername() {
  165. return username;
  166. }
  167.  
  168. public String getPassword() {
  169. return password;
  170. }
  171.  
  172. public String getCreated_at() {
  173. return created_at;
  174. }
  175.  
  176. public void setNewPassword(String newPassword) {
  177. this.newPassword = newPassword;
  178. }
  179.  
  180. public void setToken(String token) {
  181. this.token = token;
  182. }
  183.  
  184. }
  185.  
  186. public class Response {
  187.  
  188. private String message;
  189. private String token;
  190.  
  191. public String getMessage() {
  192. return message;
  193. }
  194.  
  195. public String getToken() {
  196. return token;
  197. }
  198. }
  199.  
  200. public class Constants {
  201.  
  202. public static final String BASE_URL = "http://192.168.2.145:8083/api/users/";
  203. public static final String TOKEN = "token";
  204. public static final String USERNAME = "username";
  205. //This would be the name of our shared preferences
  206. public static final String SHARED_PREF_NAME = "myloginapp";
  207.  
  208. //This would be used to store the email of current logged in user
  209. public static final String EMAIL_SHARED_PREF = "email";
  210.  
  211. //We will use this to store the boolean in sharedpreference to track user is loggedin or not
  212.  
  213. public static final String LOGGEDIN_SHARED_PREF = "loggedin";
  214. }
  215.  
  216. const User= require("../model/user.model.js");
  217. const { initSession} = require('../utils/utils');
  218.  
  219. const logins = (req,res,next)=> {
  220. console.log("login user::"+JSON.stringify(req.body));
  221. User.findOne({ username : req.body.username }, function(err, user) {
  222. if (!user) {
  223. return res.status(404).send({
  224. message : "User not found."
  225. });
  226. }
  227. else {
  228. if (user.validPassword(req.body.password)) {
  229. const sess = initSession(user._id);
  230. res
  231. .cookie('token', sess.token, {
  232. httpOnly: true,
  233. sameSite: true,
  234. maxAge: 2 * 60 * 60 * 1000
  235. })
  236. .json({
  237. title: 'Login Successful',
  238. detail: 'Successfully validated user credentials',
  239. csrfToken: sess.csrfToken,
  240. });
  241.  
  242. }
  243. else {
  244. return res.status(400).send({
  245. message : "Wrong Password"
  246. });
  247. }
  248. }
  249. })
  250. }
  251. module.exports = { logins };
  252.  
  253. module.exports = function(app) {
  254. var express = require("express");
  255. const path = require("path");
  256. const Register=require('../controllers/register.controller');
  257. const Login=require('../controllers/login.controller');
  258. var router = express.Router();
  259. router.use(function (req,res,next) {
  260. console.log("/" + req.method);
  261. next();
  262. });
  263.  
  264. app.get('/', (req, res) => res.end('Welcome to Learn2Crack !'));
  265.  
  266. //post Register details
  267. app.post('/api/users/register',Register.save);
  268.  
  269. //fetch Register details
  270. app.get('/api/users/fetchregister',Register.fetch);
  271.  
  272. //logging in a user
  273. app.post('/api/users/logins', Login.logins);
  274.  
  275.  
  276. }
Add Comment
Please, Sign In to add comment