Advertisement
Guest User

Untitled

a guest
Nov 2nd, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.61 KB | None | 0 0
  1. import android.app.Activity;
  2. import android.app.ProgressDialog;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.util.Log;
  6. import android.view.View;
  7. import android.widget.Button;
  8. import android.widget.EditText;
  9. import android.widget.Toast;
  10.  
  11. import com.android.volley.Request.Method;
  12. import com.android.volley.Response;
  13. import com.android.volley.VolleyError;
  14. import com.android.volley.toolbox.StringRequest;
  15.  
  16. import org.json.JSONException;
  17. import org.json.JSONObject;
  18.  
  19. import java.util.HashMap;
  20. import java.util.Map;
  21.  
  22. import info.androidhive.loginandregistration.R;
  23. import info.androidhive.loginandregistration.app.AppConfig;
  24. import info.androidhive.loginandregistration.app.AppController;
  25. import info.androidhive.loginandregistration.helper.SQLiteHandler;
  26. import info.androidhive.loginandregistration.helper.SessionManager;
  27.  
  28. public class RegisterActivity extends Activity {
  29. private static final String TAG = RegisterActivity.class.getSimpleName();
  30. private Button btnRegister;
  31. private Button btnLinkToLogin;
  32. private EditText inputFullName;
  33. private EditText inputEmail;
  34. private EditText inputPassword;
  35. private ProgressDialog pDialog;
  36. private SessionManager session;
  37. private SQLiteHandler db;
  38.  
  39. @Override
  40. public void onCreate(Bundle savedInstanceState) {
  41. super.onCreate(savedInstanceState);
  42. setContentView(R.layout.activity_register);
  43.  
  44. inputFullName = (EditText) findViewById(R.id.name);
  45. inputEmail = (EditText) findViewById(R.id.email);
  46. inputPassword = (EditText) findViewById(R.id.password);
  47. btnRegister = (Button) findViewById(R.id.btnRegister);
  48. btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
  49.  
  50. // Progress dialog
  51. pDialog = new ProgressDialog(this);
  52. pDialog.setCancelable(false);
  53.  
  54. // Session manager
  55. session = new SessionManager(getApplicationContext());
  56.  
  57. // SQLite database handler
  58. db = new SQLiteHandler(getApplicationContext());
  59.  
  60. // Check if user is already logged in or not
  61. if (session.isLoggedIn()) {
  62. // User is already logged in. Take him to main activity
  63. Intent intent = new Intent(RegisterActivity.this,
  64. MainActivity.class);
  65. startActivity(intent);
  66. finish();
  67. }
  68.  
  69. // Register Button Click event
  70. btnRegister.setOnClickListener(new View.OnClickListener() {
  71. public void onClick(View view) {
  72. String name = inputFullName.getText().toString().trim();
  73. String email = inputEmail.getText().toString().trim();
  74. String password = inputPassword.getText().toString().trim();
  75.  
  76. if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
  77. registerUser(name, email, password);
  78.  
  79. } else {
  80. Toast.makeText(getApplicationContext(),
  81. "Please enter your details!", Toast.LENGTH_LONG)
  82. .show();
  83. }
  84. }
  85. });
  86.  
  87. // Link to Login Screen
  88. btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
  89.  
  90. public void onClick(View view) {
  91. Intent i = new Intent(getApplicationContext(),
  92. LoginActivity.class);
  93. startActivity(i);
  94. finish();
  95. }
  96. });
  97.  
  98. }
  99.  
  100. /**
  101. * Function to store user in MySQL database will post params(tag, name,
  102. * email, password) to register url
  103. * */
  104. private void registerUser(final String name, final String email,
  105. final String password) {
  106. // Tag used to cancel the request
  107. String tag_string_req = "req_register";
  108.  
  109. pDialog.setMessage("Registering ...");
  110. showDialog();
  111.  
  112. StringRequest strReq = new StringRequest(Method.POST,
  113. AppConfig.URL_REGISTER, new Response.Listener<String>() {
  114.  
  115. @Override
  116. public void onResponse(String response) {
  117. Log.d(TAG, "Register Response: " + response.toString());
  118. hideDialog();
  119.  
  120. try {
  121. JSONObject jObj = new JSONObject(response);
  122. boolean error = jObj.getBoolean("error");
  123. if (!error) {
  124. // User successfully stored in MySQL
  125. // Now store the user in sqlite
  126. String uid = jObj.getString("uid");
  127.  
  128. JSONObject user = jObj.getJSONObject("user");
  129. String name = user.getString("name");
  130. String email = user.getString("email");
  131. String created_at = user
  132. .getString("created_at");
  133.  
  134. // Inserting row in users table
  135. db.addUser(name, email, uid, created_at);
  136.  
  137. Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
  138.  
  139. // Launch login activity
  140. Intent intent = new Intent(
  141. RegisterActivity.this,
  142. LoginActivity.class);
  143. startActivity(intent);
  144. finish();
  145. } else {
  146.  
  147. // Error occurred in registration. Get the error
  148. // message
  149. String errorMsg = jObj.getString("error_msg");
  150. Toast.makeText(getApplicationContext(),
  151. errorMsg, Toast.LENGTH_LONG).show();
  152. }
  153. } catch (JSONException e) {
  154. e.printStackTrace();
  155. }
  156.  
  157. }
  158. }, new Response.ErrorListener() {
  159.  
  160. @Override
  161. public void onErrorResponse(VolleyError error) {
  162. Log.e(TAG, "Registration Error: " + error.getMessage());
  163. Toast.makeText(getApplicationContext(),
  164. error.getMessage(), Toast.LENGTH_LONG).show();
  165. hideDialog();
  166. }
  167. }) {
  168.  
  169. @Override
  170. protected Map<String, String> getParams() {
  171. // Posting params to register url
  172. Map<String, String> params = new HashMap<String, String>();
  173. params.put("name", name);
  174. params.put("email", email);
  175. params.put("password", password);
  176.  
  177. return params;
  178. }
  179.  
  180. };
  181.  
  182. // Adding request to request queue
  183. AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
  184. }
  185.  
  186. private void showDialog() {
  187. if (!pDialog.isShowing())
  188. pDialog.show();
  189. }
  190.  
  191. private void hideDialog() {
  192. if (pDialog.isShowing())
  193. pDialog.dismiss();
  194. }``
  195. }
  196.  
  197. public class AppConfig {
  198. // Server user login url
  199. public static String URL_LOGIN = "http://my_ip_address/android_login_api/login.php";
  200.  
  201. // Server user register url
  202. public static String URL_REGISTER = "http://my_ip_address/android_login_api/register.php";
  203. }
  204.  
  205. DB_Connect.php
  206. <?php
  207. class DB_Connect {
  208. private $conn;
  209.  
  210. // Connecting to database
  211. public function connect() {
  212. require_once 'include/Config.php';
  213.  
  214. // Connecting to mysql database
  215. $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
  216.  
  217. // return database handler
  218. return $this->conn;
  219. }
  220. }
  221.  
  222. ?>
  223.  
  224. <?php
  225.  
  226. /**
  227. * Database config variables
  228. */
  229. define("DB_HOST", "localhost");
  230. define("DB_USER", "root");
  231. define("DB_PASSWORD", "root");
  232. define("DB_DATABASE", "android_api");
  233. ?>
  234.  
  235. require_once 'include/DB_Functions.php';
  236. $db = new DB_Functions();
  237.  
  238. // json response array
  239. $response = array("error" => FALSE);
  240.  
  241. if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password'])) {
  242.  
  243. // receiving the post params
  244. $name = $_POST['name'];
  245. $email = $_POST['email'];
  246. $password = $_POST['password'];
  247.  
  248. // check if user is already existed with the same email
  249. if ($db->isUserExisted($email)) {
  250. // user already existed
  251. $response["error"] = TRUE;
  252. $response["error_msg"] = "User already existed with " . $email;
  253. echo json_encode($response);
  254. } else {
  255. // create a new user
  256. $user = $db->storeUser($name, $email, $password);
  257. if ($user) {
  258. // user stored successfully
  259. $response["error"] = FALSE;
  260. $response["uid"] = $user["unique_id"];
  261. $response["user"]["name"] = $user["name"];
  262. $response["user"]["email"] = $user["email"];
  263. $response["user"]["created_at"] = $user["created_at"];
  264. $response["user"]["updated_at"] = $user["updated_at"];
  265. echo json_encode($response);
  266. } else {
  267. // user failed to store
  268. $response["error"] = TRUE;
  269. $response["error_msg"] = "Unknown error occurred in registration!";
  270. echo json_encode($response);
  271. }
  272. }
  273. } else {
  274. $response["error"] = TRUE;
  275. $response["error_msg"] = "Required parameters (name, email or password) is missing!";
  276. echo json_encode($response);
  277. }
  278. ?>
  279.  
  280. class DB_Functions {
  281.  
  282. private $conn;
  283.  
  284. // constructor
  285. function __construct() {
  286. require_once 'DB_Connect.php';
  287. // connecting to database
  288. $db = new Db_Connect();
  289. $this->conn = $db->connect();
  290. }
  291.  
  292. // destructor
  293. function __destruct() {
  294.  
  295. }
  296.  
  297. /**
  298. * Storing new user
  299. * returns user details
  300. */
  301. public function storeUser($name, $email, $password) {
  302. $uuid = uniqid('', true);
  303. $hash = $this->hashSSHA($password);
  304. $encrypted_password = $hash["encrypted"]; // encrypted password
  305. $salt = $hash["salt"]; // salt
  306.  
  307. $stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES(?, ?, ?, ?, ?, NOW())");
  308. $stmt->bind_param("sssss", $uuid, $name, $email, $encrypted_password, $salt);
  309. $result = $stmt->execute();
  310. $stmt->close();
  311.  
  312. // check for successful store
  313. if ($result) {
  314. $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
  315. $stmt->bind_param("s", $email);
  316. $stmt->execute();
  317. $user = $stmt->get_result()->fetch_assoc();
  318. $stmt->close();
  319.  
  320. return $user;
  321. } else {
  322. return false;
  323. }
  324. }
  325.  
  326. /**
  327. * Get user by email and password
  328. */
  329. public function getUserByEmailAndPassword($email, $password) {
  330.  
  331. $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
  332.  
  333. $stmt->bind_param("s", $email);
  334.  
  335. if ($stmt->execute()) {
  336. $user = $stmt->get_result()->fetch_assoc();
  337. $stmt->close();
  338.  
  339. // verifying user password
  340. $salt = $user['salt'];
  341. $encrypted_password = $user['encrypted_password'];
  342. $hash = $this->checkhashSSHA($salt, $password);
  343. // check for password equality
  344. if ($encrypted_password == $hash) {
  345. // user authentication details are correct
  346. return $user;
  347. }
  348. } else {
  349. return NULL;
  350. }
  351. }
  352.  
  353. /**
  354. * Check user is existed or not
  355. */
  356. public function isUserExisted($email) {
  357. $stmt = $this->conn->prepare("SELECT email from users WHERE email = ?");
  358.  
  359. $stmt->bind_param("s", $email);
  360.  
  361. $stmt->execute();
  362.  
  363. $stmt->store_result();
  364.  
  365. if ($stmt->num_rows > 0) {
  366. // user existed
  367. $stmt->close();
  368. return true;
  369. } else {
  370. // user not existed
  371. $stmt->close();
  372. return false;
  373. }
  374. }
  375.  
  376. /**
  377. * Encrypting password
  378. * @param password
  379. * returns salt and encrypted password
  380. */
  381. public function hashSSHA($password) {
  382.  
  383. $salt = sha1(rand());
  384. $salt = substr($salt, 0, 10);
  385. $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
  386. $hash = array("salt" => $salt, "encrypted" => $encrypted);
  387. return $hash;
  388. }
  389.  
  390. /**
  391. * Decrypting password
  392. * @param salt, password
  393. * returns hash string
  394. */
  395. public function checkhashSSHA($salt, $password) {
  396.  
  397. $hash = base64_encode(sha1($password . $salt, true) . $salt);
  398.  
  399. return $hash;
  400. }
  401.  
  402. }
  403.  
  404. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement