Commit cca9143989948ee5e7307c3e410fe989a16a0f4d

Authored by Ali B
1 parent 46617988

Working on login, encryption and tokens. Now hashing and unhashing of password i…

…s working on the server side, only tokens left to complete
Showing 56 changed files with 1757 additions and 100 deletions   Show diff stats
Risiko/app/src/main/AndroidManifest.xml
... ... @@ -18,6 +18,11 @@
18 18 <category android:name="android.intent.category.LAUNCHER" />
19 19 </intent-filter>
20 20 </activity>
  21 +
  22 + <service
  23 + android:name="api.APILoginService"
  24 + android:exported="false" />
  25 +
21 26 <activity android:name="activity.MainMenu" />
22 27 <activity android:name="activity.Activities" />
23 28 <activity android:name="activity.Incident" />
... ...
Risiko/app/src/main/java/activity/Activities.java
... ... @@ -12,10 +12,10 @@ import android.widget.Toast;
12 12  
13 13 import com.risiko.risiko.R;
14 14  
15   -import java.util.ArrayList;
16 15 import java.util.List;
17 16 import adapters.ListAdapterActivities;
18 17 import api.Api;
  18 +import api.TokenEncrypter;
19 19 import dataclasses.Activity;
20 20 import retrofit2.Call;
21 21 import retrofit2.Callback;
... ... @@ -23,6 +23,7 @@ import retrofit2.Response;
23 23  
24 24 public class Activities extends AppCompatActivity {
25 25 ListView lv;
  26 + String token;
26 27  
27 28 @Override
28 29 protected void onCreate(Bundle savedInstanceState) {
... ... @@ -31,7 +32,9 @@ public class Activities extends AppCompatActivity {
31 32 Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
32 33 setSupportActionBar(myToolbar);
33 34  
34   - Api.get().getAllActivities()
  35 + token = TokenEncrypter.getToken(this);
  36 +
  37 + Api.get().getAllActivities(token)
35 38 .enqueue(new Callback<List<Activity>>() {
36 39 @Override
37 40 public void onResponse(Call<List<Activity>> call, Response<List<Activity>> response) {
... ...
Risiko/app/src/main/java/activity/EditIncident.java
... ... @@ -19,6 +19,7 @@ import java.util.HashMap;
19 19 import java.util.List;
20 20  
21 21 import api.Api;
  22 +import api.TokenEncrypter;
22 23 import dataclasses.Evaluation;
23 24 import dataclasses.Incident;
24 25 import retrofit2.Call;
... ... @@ -32,6 +33,7 @@ public class EditIncident extends AppCompatActivity {
32 33 private EditText etDescription;
33 34 private Button editIncident;
34 35 private Spinner spinnerAssociatedRisk;
  36 + private String token;
35 37  
36 38 @Override
37 39 protected void onCreate(Bundle savedInstanceState) {
... ... @@ -40,6 +42,8 @@ public class EditIncident extends AppCompatActivity {
40 42 Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
41 43 setSupportActionBar(myToolbar);
42 44  
  45 + token = TokenEncrypter.getToken(this);
  46 +
43 47 Intent intent = getIntent();
44 48 Bundle b = intent.getExtras();
45 49 String id = b.getString("chosenEventId");
... ... @@ -63,7 +67,7 @@ public class EditIncident extends AppCompatActivity {
63 67  
64 68 spinnerAssociatedRisk = findViewById(R.id.spinner_associated_risk);
65 69  
66   - Api.get().getAllEvaluations()
  70 + Api.get().getAllEvaluations(token)
67 71 .enqueue(new Callback<List<Evaluation>>() {
68 72  
69 73 @Override
... ... @@ -86,7 +90,7 @@ public class EditIncident extends AppCompatActivity {
86 90 String newlocation = etLocation.getText().toString();
87 91 String newdescription = etDescription.getText().toString();
88 92  
89   - Api.get().editIncident(id, newdate, newlocation, newtitle, newdescription, associatedRisk).enqueue(new Callback<dataclasses.Incident>() {
  93 + Api.get().editIncident(id, newdate, newlocation, newtitle, newdescription, associatedRisk, token).enqueue(new Callback<dataclasses.Incident>() {
90 94 @Override
91 95 public void onResponse(Call<Incident> call, Response<Incident> response) {
92 96 System.out.println(response);
... ...
Risiko/app/src/main/java/activity/Evaluations.java
... ... @@ -25,6 +25,7 @@ import java.util.List;
25 25 import adapters.ListAdapterEvaluations;
26 26  
27 27 import api.Api;
  28 +import api.TokenEncrypter;
28 29 import database.DatabaseSource;
29 30 import dataclasses.Evaluation;
30 31 import retrofit2.Call;
... ... @@ -37,6 +38,7 @@ public class Evaluations extends AppCompatActivity {
37 38 Button btnNewEvaluation;
38 39 DatabaseSource dbs;
39 40 String id;
  41 + String token;
40 42  
41 43 @Override
42 44 protected void onCreate(Bundle savedInstanceState) {
... ... @@ -45,6 +47,7 @@ public class Evaluations extends AppCompatActivity {
45 47 Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
46 48 setSupportActionBar(myToolbar);
47 49  
  50 + token = TokenEncrypter.getToken(this);
48 51  
49 52 dbs = new DatabaseSource(this);
50 53  
... ... @@ -54,7 +57,7 @@ public class Evaluations extends AppCompatActivity {
54 57 System.out.println(activityId);
55 58  
56 59  
57   - Api.get().getAllEvaluations()
  60 + Api.get().getAllEvaluations(token)
58 61 .enqueue(new Callback<List<Evaluation>>() {
59 62 @Override
60 63 public void onResponse(Call<List<Evaluation>> call, Response<List<Evaluation>> response) {
... ...
Risiko/app/src/main/java/activity/Incident.java
... ... @@ -26,6 +26,7 @@ import java.util.List;
26 26  
27 27 import adapters.ListAdapterIncidents;
28 28 import api.Api;
  29 +import api.TokenEncrypter;
29 30 import database.DatabaseSource;
30 31 import dataclasses.Evaluation;
31 32 import retrofit2.Call;
... ... @@ -37,6 +38,7 @@ public class Incident extends AppCompatActivity {
37 38 String chosenEventId;
38 39 DatabaseSource dbs;
39 40 String id;
  41 + String token;
40 42  
41 43 @Override
42 44 protected void onCreate(Bundle savedInstanceState) {
... ... @@ -46,6 +48,7 @@ public class Incident extends AppCompatActivity {
46 48 Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
47 49 setSupportActionBar(myToolbar);
48 50  
  51 + token = TokenEncrypter.getToken(this);
49 52  
50 53 dbs = new DatabaseSource(this);
51 54  
... ... @@ -54,7 +57,7 @@ public class Incident extends AppCompatActivity {
54 57 // insertEvents(incidentList);
55 58  
56 59  
57   - Api.get().getAllIncidents()
  60 + Api.get().getAllIncidents(token)
58 61 .enqueue(new Callback<List<dataclasses.Incident>>() {
59 62  
60 63 @Override
... ... @@ -123,7 +126,7 @@ public class Incident extends AppCompatActivity {
123 126  
124 127  
125 128 System.out.println("EVALID" + chosenItem.getAssociatedeval());
126   - Api.get().getEvaluation(chosenItem.getAssociatedeval()).enqueue(new Callback<Evaluation>() {
  129 + Api.get().getEvaluation(chosenItem.getAssociatedeval(), token).enqueue(new Callback<Evaluation>() {
127 130 @Override
128 131 public void onResponse(Call<Evaluation> call, Response<Evaluation> response) {
129 132 Evaluation evaluation = response.body();
... ... @@ -179,7 +182,7 @@ public class Incident extends AppCompatActivity {
179 182 @Override
180 183 public void onClick(DialogInterface dialogInterface, int i) {
181 184  
182   - Api.get().deleteIncident(chosenEventId).enqueue(new Callback<String>() {
  185 + Api.get().deleteIncident(chosenEventId, token).enqueue(new Callback<String>() {
183 186 @Override
184 187 public void onResponse(Call<String> call, Response<String> response) {
185 188 finish();
... ...
Risiko/app/src/main/java/activity/MainPage.java
... ... @@ -10,6 +10,7 @@ import android.view.View;
10 10 import android.widget.Button;
11 11 import android.widget.EditText;
12 12 import android.widget.TextView;
  13 +import android.widget.Toast;
13 14  
14 15 import com.risiko.risiko.R;
15 16  
... ... @@ -17,15 +18,17 @@ import api.APILoginService;
17 18  
18 19 public class MainPage extends AppCompatActivity {
19 20 Button toMainMenu;
20   - private EditText mUsernameView;
21   - private EditText mPasswordView;
  21 + private EditText etUsernameView;
  22 + private EditText etPasswordView;
22 23  
23 24 @Override
24 25 protected void onCreate(Bundle savedInstanceState) {
25 26 super.onCreate(savedInstanceState);
26 27 setContentView(R.layout.activity_main_page);
27 28 toMainMenu = findViewById(R.id.btn_to_main_menu);
28   - toMainMenu.setOnClickListener(view -> toMainMenuEvent());
  29 + toMainMenu.setOnClickListener(view -> attemptLogin());
  30 + etUsernameView = findViewById(R.id.et_username);
  31 + etPasswordView = findViewById(R.id.et_password);
29 32 }
30 33  
31 34 public void toMainMenuEvent(){
... ... @@ -40,39 +43,44 @@ public class MainPage extends AppCompatActivity {
40 43 *
41 44 */
42 45 private void attemptLogin() {
  46 + System.out.println("0");
43 47  
44   - mUsernameView.setError(null);
45   - mPasswordView.setError(null);
  48 + etUsernameView.setError(null);
  49 + etPasswordView.setError(null);
46 50  
47   - String username = mUsernameView.getText().toString();
48   - String password = mPasswordView.getText().toString();
  51 + String username = etUsernameView.getText().toString();
  52 + String password = etPasswordView.getText().toString();
49 53  
50 54 boolean cancel = false;
51 55 View focusView = null;
52 56  
53 57 // Checking password input
54 58 if (TextUtils.isEmpty(password) && !isPasswordValid(password)) {
55   - mPasswordView.setError(getString(R.string.error_invalid_password));
56   - focusView = mPasswordView;
  59 + System.out.println("1");
  60 + etPasswordView.setError(getString(R.string.error_invalid_password));
  61 + focusView = etPasswordView;
57 62 cancel = true;
58 63 }
59 64  
60 65 // Checking username input.
61 66 if (TextUtils.isEmpty(username)) {
62   - mUsernameView.setError(getString(R.string.error_field_required));
63   - focusView = mUsernameView;
  67 + System.out.println("2");
  68 + etUsernameView.setError(getString(R.string.error_field_required));
  69 + focusView = etUsernameView;
64 70 cancel = true;
65 71 } else if (!isUsernameValid(username)) {
66   - mUsernameView.setError(getString(R.string.error_invalid_username));
67   - focusView = mUsernameView;
  72 + System.out.println("2,1");
  73 + etUsernameView.setError(getString(R.string.error_invalid_username));
  74 + focusView = etUsernameView;
68 75 cancel = true;
69 76 }
70 77  
71 78 if (cancel) {
72 79 focusView.requestFocus();
73 80 } else {
  81 + System.out.println("3");
74 82 //Connecting to server and checking login credentials.
75   - APILoginService.startActionLogin(this, mPasswordView.getText().toString(), mUsernameView.getText().toString());
  83 + APILoginService.startActionLogin(this, etPasswordView.getText().toString(), etUsernameView.getText().toString());
76 84 }
77 85 }
78 86  
... ... @@ -100,8 +108,10 @@ public class MainPage extends AppCompatActivity {
100 108 break;
101 109  
102 110 // Code for success
103   - case 201:
  111 + case 202:
104 112 //TODO: Success, go to main menu
  113 + System.out.println("LOGIN");
  114 + Toast.makeText(getBaseContext(), "Halla brusjan success", Toast.LENGTH_LONG).show();
105 115 break;
106 116  
107 117 // Error from php server.
... ... @@ -139,7 +149,7 @@ public class MainPage extends AppCompatActivity {
139 149 * @return true if it is valid.
140 150 */
141 151 public static boolean isUsernameValid(String username) {
142   - return username.length() > 5;
  152 + return username.length() > 3;
143 153 }
144 154  
145 155 }
146 156 \ No newline at end of file
... ...
Risiko/app/src/main/java/activity/NewEvaluation.java
... ... @@ -18,6 +18,7 @@ import java.util.HashMap;
18 18 import java.util.UUID;
19 19  
20 20 import api.Api;
  21 +import api.TokenEncrypter;
21 22 import database.DatabaseSource;
22 23 import dataclasses.Evaluation;
23 24 import retrofit2.Call;
... ... @@ -30,6 +31,7 @@ public class NewEvaluation extends AppCompatActivity {
30 31 private Spinner spinnerConsequence, spinnerProbability;
31 32 private Button btnNewEval;
32 33 DatabaseSource dbs;
  34 + String token;
33 35  
34 36 @Override
35 37 protected void onCreate(Bundle savedInstanceState) {
... ... @@ -38,6 +40,7 @@ public class NewEvaluation extends AppCompatActivity {
38 40 Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
39 41 setSupportActionBar(myToolbar);
40 42  
  43 + token = TokenEncrypter.getToken(this);
41 44  
42 45 Intent intent = getIntent();
43 46 String activityId = intent.getStringExtra("ID_OF_CHOSEN_ACTIVITY");
... ... @@ -61,7 +64,7 @@ public class NewEvaluation extends AppCompatActivity {
61 64 int consequenceValue = getConsequenceValue(consequence);
62 65 int probabilityValue = getProbabilityValue(probability);
63 66  
64   - Api.get().newEvaluation(title, UUID.randomUUID().toString() ,activityId,consequenceValue,action,outcome,probabilityValue).enqueue(new Callback<String>() {
  67 + Api.get().newEvaluation(title, UUID.randomUUID().toString() ,activityId,consequenceValue,action,outcome,probabilityValue, token).enqueue(new Callback<String>() {
65 68 @Override
66 69 public void onResponse(Call<String> call, Response<String> response) {
67 70 System.out.println(response);
... ...
Risiko/app/src/main/java/activity/NewIncident.java
... ... @@ -21,6 +21,7 @@ import java.util.List;
21 21 import java.util.UUID;
22 22  
23 23 import api.Api;
  24 +import api.TokenEncrypter;
24 25 import database.DatabaseSource;
25 26 import dataclasses.Evaluation;
26 27 import dataclasses.Incident;
... ... @@ -35,6 +36,7 @@ public class NewIncident extends AppCompatActivity {
35 36 private Button btnNewIncident;
36 37 private DatabaseSource dbs;
37 38 private Spinner spinnerReadAccess;
  39 + private String token;
38 40  
39 41 @Override
40 42 protected void onCreate(Bundle savedInstanceState) {
... ... @@ -43,6 +45,7 @@ public class NewIncident extends AppCompatActivity {
43 45 Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
44 46 setSupportActionBar(myToolbar);
45 47  
  48 + token = TokenEncrypter.getToken(this);
46 49  
47 50 etDate = findViewById(R.id.et_newIncident_date);
48 51 etLocation = findViewById(R.id.et_newIncident_location);
... ... @@ -67,7 +70,7 @@ public class NewIncident extends AppCompatActivity {
67 70  
68 71 // dbs.getAllEvaluation(evaluations);
69 72  
70   - Api.get().getAllEvaluations()
  73 + Api.get().getAllEvaluations(token)
71 74 .enqueue(new Callback<List<Evaluation>>() {
72 75  
73 76 @Override
... ... @@ -94,7 +97,7 @@ public class NewIncident extends AppCompatActivity {
94 97 dataclasses.Incident newIncident = new Incident(id, date, location, title, description, associatedRisk);
95 98  
96 99  
97   - Api.get().newIncident(date, title, id, associatedRisk, description, location).enqueue(new Callback<String>() {
  100 + Api.get().newIncident(date, title, id, associatedRisk, description, location, token).enqueue(new Callback<String>() {
98 101 @Override
99 102 public void onResponse(Call<String> call, Response<String> response) {
100 103 System.out.println(response);
... ...
Risiko/app/src/main/java/api/APILoginService.java
... ... @@ -5,16 +5,10 @@ import android.content.Context;
5 5 import android.content.Intent;
6 6 import android.content.SharedPreferences;
7 7 import android.support.v4.content.LocalBroadcastManager;
  8 +import android.widget.Toast;
8 9  
9 10 import com.risiko.risiko.R;
10 11  
11   -import java.io.BufferedReader;
12   -import java.io.IOException;
13   -import java.io.InputStreamReader;
14   -import java.io.OutputStreamWriter;
15   -import java.net.HttpURLConnection;
16   -import java.net.URL;
17   -
18 12 import activity.MainPage;
19 13 import retrofit2.Call;
20 14 import retrofit2.Callback;
... ... @@ -23,24 +17,24 @@ import retrofit2.Response;
23 17  
24 18 /**
25 19 * Service for login.
26   - * Makes contact with API on stored URL. API checks for correct password and email.
  20 + * Makes contact with API on stored URL. API checks for correct password and username.
27 21 * Sends broadcast with response. Does not handle repsonse in class.
28 22 */
29 23 public class APILoginService extends IntentService {
30 24  
31   - private static final String ACTION_LOGIN = "prosjekt.rapporteringsapp.Services.action.LOGIN";
32   - private static final String EXTRA_PASSWORD = "prosjekt.rapporteringsapp.Services.extra.PASSWORD";
33   - private static final String EXTRA_EMAIL = "prosjekt.rapporteringsapp.Services.extra.EMAIL";
  25 + private static final String ACTION_LOGIN = "risk.api.action.LOGIN";
  26 + private static final String EXTRA_PASSWORD = "risk.api.extra.PASSWORD";
  27 + private static final String EXTRA_USERNAME = "risk.api.extra.EMAIL";
34 28  
35 29 public APILoginService() {
36 30 super("APIServiceLogin");
37 31 }
38 32  
39   - public static void startActionLogin(Context context, String password, String email) {
  33 + public static void startActionLogin(Context context, String password, String username) {
40 34 Intent intent = new Intent(context, APILoginService.class);
41 35 intent.setAction(ACTION_LOGIN);
42 36 intent.putExtra(EXTRA_PASSWORD, password);
43   - intent.putExtra(EXTRA_EMAIL, email);
  37 + intent.putExtra(EXTRA_USERNAME, username);
44 38 context.startService(intent);
45 39 }
46 40  
... ... @@ -50,8 +44,8 @@ public class APILoginService extends IntentService {
50 44 final String action = intent.getAction();
51 45 if (ACTION_LOGIN.equals(action)) {
52 46 final String password = intent.getStringExtra(EXTRA_PASSWORD);
53   - final String email = intent.getStringExtra(EXTRA_EMAIL);
54   - handleActionLogin(password, email);
  47 + final String username = intent.getStringExtra(EXTRA_USERNAME);
  48 + handleActionLogin(password, username);
55 49 }
56 50 }
57 51 }
... ... @@ -68,10 +62,9 @@ public class APILoginService extends IntentService {
68 62 private void handleActionLogin(String password, String username) throws NullPointerException {
69 63  
70 64  
71   - Api.get().login(password, username).enqueue(new Callback<String>() {
  65 + Api.get().login(username, password).enqueue(new Callback<String>() {
72 66 @Override
73 67 public void onResponse(Call<String> call, Response<String> response) {
74   - BufferedReader reader;
75 68 if (response.code() == 202) {
76 69 String token = response.body();
77 70  
... ... @@ -87,7 +80,8 @@ public class APILoginService extends IntentService {
87 80  
88 81 @Override
89 82 public void onFailure(Call<String> call, Throwable t) {
90   -
  83 + System.out.println("Something went wrong");
  84 + System.out.println(t.getMessage());
91 85 }
92 86 });
93 87  
... ... @@ -159,7 +153,7 @@ public class APILoginService extends IntentService {
159 153 * This method encrypts given string with DESede algorithm. With key stored in strings value.
160 154 */
161 155 private String encryptToken(String token){
162   - MyEncryption encrypter = new MyEncryption();
  156 + TokenEncrypter encrypter = new TokenEncrypter();
163 157 return encrypter.encrypt(token, getString(R.string.encryption_key));
164 158 }
165 159 }
... ...
Risiko/app/src/main/java/api/Endpoints.java
... ... @@ -25,54 +25,63 @@ public interface Endpoints {
25 25  
26 26  
27 27 // THE BASEURL HAS TO BE CHANGE TO THE IP-ADDRESS YOU ARE CONNECTED TO AT LOCALHOST
28   - //String BASEURL = "http://172.20.10.4:3000/";
  28 +
  29 + //HOS ALI
  30 + String BASEURL = "http://172.20.10.4:3000/";
29 31  
30 32 //HOS KRISTIN
31   - String BASEURL = "http://192.168.84.67:3000/";
  33 +// String BASEURL = "http://192.168.84.67:3000/";
32 34  
33 35 //ØYVIN FIX
34 36 //String BASEURL ="http://risikoapi.harm.no/";
35 37  
  38 + @FormUrlEncoded
36 39 @POST("login")
37 40 Call<String> login(@Field("username") String username, @Field("password") String password);
38 41  
  42 + @FormUrlEncoded
39 43 @GET("evaluation")
40   - Call<List<Evaluation>> getAllEvaluations();
  44 + Call<List<Evaluation>> getAllEvaluations(@Field("token") String token);
41 45  
  46 + @FormUrlEncoded
42 47 @GET("evaluation/{id}")
43   - Call<Evaluation> getEvaluation(@Path("id") String id);
  48 + Call<Evaluation> getEvaluation(@Path("id") String id, @Field("token") String token);
44 49  
  50 + @FormUrlEncoded
45 51 @GET("activity")
46   - Call<List<Activity>> getAllActivities();
  52 + Call<List<Activity>> getAllActivities(@Field("token") String token);
47 53  
  54 + @FormUrlEncoded
48 55 @GET("incident")
49   - Call<List<Incident>> getAllIncidents();
  56 + Call<List<Incident>> getAllIncidents(@Field("token") String token);
50 57  
  58 + @FormUrlEncoded
51 59 @GET("incident/{id}")
52   - Call<List<Incident>> getIncident(@Path("id") String id);
  60 + Call<List<Incident>> getIncident(@Path("id") String id, @Field("token") String token);
53 61  
54 62 @FormUrlEncoded
55 63 @POST("incident")
56 64 Call<String> newIncident(@Field("date") String date, @Field("title") String title, @Field("id") String id, @Field("associatedEval") String associatedEval,
57   - @Field("description") String description, @Field("location") String location);
  65 + @Field("description") String description, @Field("location") String location, @Field("token") String token);
58 66  
59 67 @FormUrlEncoded
60 68 @POST("evaluation")
61 69 Call<String> newEvaluation(@Field("title") String title, @Field("id") String id, @Field("associatedActivity") String associatedactivity,
62   - @Field("consequence") int consequence, @Field("measures") String measures, @Field("outcome") String outcome, @Field("probability") int probability);
  70 + @Field("consequence") int consequence, @Field("measures") String measures, @Field("outcome") String outcome, @Field("probability") int probability, @Field("token") String token);
63 71  
  72 + @FormUrlEncoded
64 73 @DELETE("incident/{id}")
65   - Call<String> deleteIncident(@Path("id") String id);
  74 + Call<String> deleteIncident(@Path("id") String id, @Field("token") String token);
66 75  
67 76 @FormUrlEncoded
68 77 @DELETE("evaluation/{id}")
69   - Call<String> deleteEvaluation(@Path("id") String id);
  78 + Call<String> deleteEvaluation(@Path("id") String id, @Field("token") String token);
70 79  
71 80  
72 81 @FormUrlEncoded
73 82 @PATCH("incident/{id}")
74 83 Call<Incident> editIncident(@Path("id") String id, @Field("date") String date, @Field("location") String location,
75   - @Field("title") String title, @Field("description") String description, @Field("associatedEval") String associatedEval);
  84 + @Field("title") String title, @Field("description") String description, @Field("associatedEval") String associatedEval, @Field("token") String token);
76 85  
77 86  
78 87 }
... ...
Risiko/app/src/main/java/api/MyEncryption.java renamed to Risiko/app/src/main/java/api/TokenEncrypter.java
1 1 package api;
2 2  
  3 +import android.content.Context;
  4 +import android.content.SharedPreferences;
3 5 import android.util.Base64;
4 6  
  7 +import com.risiko.risiko.R;
  8 +
5 9 import java.io.UnsupportedEncodingException;
6 10 import java.security.GeneralSecurityException;
7 11 import java.security.spec.KeySpec;
... ... @@ -15,10 +19,19 @@ import javax.crypto.spec.DESedeKeySpec;
15 19 /**
16 20 * Class for encrypting and decrypting login token. With given key.
17 21 */
18   -public class MyEncryption {
  22 +public class TokenEncrypter {
19 23  
20 24 // Empty constructor
21   - public MyEncryption(){}
  25 + public TokenEncrypter(){}
  26 +
  27 + public static String getToken(Context context) {
  28 + SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.packageName), Context.MODE_PRIVATE);
  29 + String token = sharedPref.getString(context.getString(R.string.preference_name_token),"");
  30 + if (!token.equals(""))
  31 + return new TokenEncrypter().decrypt(token, context.getString(R.string.encryption_key));
  32 +
  33 + return "";
  34 + }
22 35  
23 36 /**
24 37 * @param stringToEncrypt The string you want to encrypt.
... ...
Thumbs.db
No preview for this file type
restApi/.idea/workspace.xml
... ... @@ -2,11 +2,10 @@
2 2 <project version="4">
3 3 <component name="ChangeListManager">
4 4 <list default="true" id="0e20d303-9de8-4113-bfd9-019e72b304dc" name="Default" comment="">
5   - <change beforePath="$PROJECT_DIR$/../Risiko/app/src/main/java/api/APILoginService.java" beforeDir="false" afterPath="$PROJECT_DIR$/../Risiko/app/src/main/java/api/APILoginService.java" afterDir="false" />
6   - <change beforePath="$PROJECT_DIR$/../Risiko/app/src/main/java/api/Endpoints.java" beforeDir="false" afterPath="$PROJECT_DIR$/../Risiko/app/src/main/java/api/Endpoints.java" afterDir="false" />
7   - <change beforePath="$PROJECT_DIR$/../Risiko/app/src/main/res/values/strings.xml" beforeDir="false" afterPath="$PROJECT_DIR$/../Risiko/app/src/main/res/values/strings.xml" afterDir="false" />
8 5 <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
9 6 <change beforePath="$PROJECT_DIR$/api/routes/routes.js" beforeDir="false" afterPath="$PROJECT_DIR$/api/routes/routes.js" afterDir="false" />
  7 + <change beforePath="$PROJECT_DIR$/package-lock.json" beforeDir="false" afterPath="$PROJECT_DIR$/package-lock.json" afterDir="false" />
  8 + <change beforePath="$PROJECT_DIR$/package.json" beforeDir="false" afterPath="$PROJECT_DIR$/package.json" afterDir="false" />
10 9 </list>
11 10 <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
12 11 <option name="SHOW_DIALOG" value="false" />
... ... @@ -18,34 +17,37 @@
18 17 <session id="535790383">
19 18 <usages-collector id="statistics.lifecycle.project">
20 19 <counts>
21   - <entry key="project.closed" value="2" />
  20 + <entry key="project.closed" value="4" />
22 21 <entry key="project.open.time.1" value="1" />
23 22 <entry key="project.open.time.10" value="1" />
24 23 <entry key="project.open.time.24" value="1" />
  24 + <entry key="project.open.time.26" value="1" />
25 25 <entry key="project.open.time.31" value="1" />
26   - <entry key="project.opened" value="4" />
  26 + <entry key="project.opened" value="5" />
27 27 </counts>
28 28 </usages-collector>
29 29 <usages-collector id="statistics.file.extensions.edit">
30 30 <counts>
31   - <entry key="js" value="3248" />
  31 + <entry key="js" value="6072" />
  32 + <entry key="json" value="42" />
32 33 </counts>
33 34 </usages-collector>
34 35 <usages-collector id="statistics.file.types.edit">
35 36 <counts>
36   - <entry key="JavaScript" value="3248" />
  37 + <entry key="JSON" value="42" />
  38 + <entry key="JavaScript" value="6072" />
37 39 </counts>
38 40 </usages-collector>
39 41 <usages-collector id="statistics.file.types.open">
40 42 <counts>
41   - <entry key="JavaScript" value="1" />
  43 + <entry key="JavaScript" value="2" />
42 44 </counts>
43 45 </usages-collector>
44 46 <usages-collector id="statistics.vcs.git.usages" />
45 47 <usages-collector id="statistics.js.language.service.starts" />
46 48 <usages-collector id="statistics.file.extensions.open">
47 49 <counts>
48   - <entry key="js" value="1" />
  50 + <entry key="js" value="2" />
49 51 </counts>
50 52 </usages-collector>
51 53 </session>
... ... @@ -55,8 +57,8 @@
55 57 <file pinned="false" current-in-tab="true">
56 58 <entry file="file://$PROJECT_DIR$/api/routes/routes.js">
57 59 <provider selected="true" editor-type-id="text-editor">
58   - <state relative-caret-position="415">
59   - <caret line="357" column="50" selection-start-line="357" selection-start-column="50" selection-end-line="357" selection-end-column="50" />
  60 + <state relative-caret-position="173">
  61 + <caret line="55" column="62" selection-start-line="55" selection-start-column="62" selection-end-line="55" selection-end-column="62" />
60 62 </state>
61 63 </provider>
62 64 </entry>
... ... @@ -64,8 +66,8 @@
64 66 <file pinned="false" current-in-tab="false">
65 67 <entry file="file://$PROJECT_DIR$/package.json">
66 68 <provider selected="true" editor-type-id="text-editor">
67   - <state relative-caret-position="153">
68   - <caret line="9" column="4" selection-start-line="9" selection-start-column="4" selection-end-line="9" selection-end-column="4" />
  69 + <state relative-caret-position="120">
  70 + <caret line="8" column="38" selection-start-line="8" selection-start-column="38" selection-end-line="8" selection-end-column="38" />
69 71 </state>
70 72 </provider>
71 73 </entry>
... ... @@ -75,6 +77,7 @@
75 77 <component name="FindInProjectRecents">
76 78 <findStrings>
77 79 <find>delete</find>
  80 + <find>token</find>
78 81 </findStrings>
79 82 </component>
80 83 <component name="Git.Settings">
... ... @@ -105,9 +108,11 @@
105 108 </packageJsonPaths>
106 109 </component>
107 110 <component name="PhpWorkspaceProjectConfiguration" backward_compatibility_performed="true" />
108   - <component name="ProjectFrameBounds" extendedState="7">
109   - <option name="width" value="1920" />
110   - <option name="height" value="1080" />
  111 + <component name="ProjectFrameBounds" extendedState="6">
  112 + <option name="x" value="-1374" />
  113 + <option name="y" value="471" />
  114 + <option name="width" value="1382" />
  115 + <option name="height" value="784" />
111 116 </component>
112 117 <component name="ProjectView">
113 118 <navigator proportions="" version="1">
... ... @@ -148,6 +153,7 @@
148 153 <component name="PropertiesComponent">
149 154 <property name="WebServerToolWindowFactoryState" value="false" />
150 155 <property name="nodejs_package_manager_path" value="npm" />
  156 + <property name="settings.editor.selected.configurable" value="editor.preferences.fonts.default" />
151 157 </component>
152 158 <component name="RunDashboard">
153 159 <option name="ruleStates">
... ... @@ -192,8 +198,8 @@
192 198 </list>
193 199 <recent_temporary>
194 200 <list>
195   - <item itemvalue="npm.debug" />
196 201 <item itemvalue="npm.api" />
  202 + <item itemvalue="npm.debug" />
197 203 <item itemvalue="Node.js.server.js" />
198 204 </list>
199 205 </recent_temporary>
... ... @@ -218,30 +224,30 @@
218 224 <workItem from="1542894129000" duration="445000" />
219 225 <workItem from="1543239135040" duration="1484000" />
220 226 <workItem from="1543323597689" duration="1776000" />
  227 + <workItem from="1543397623259" duration="14429000" />
221 228 </task>
222 229 <servers />
223 230 </component>
224 231 <component name="TimeTrackingManager">
225   - <option name="totallyTimeSpent" value="33149000" />
  232 + <option name="totallyTimeSpent" value="60958000" />
226 233 </component>
227 234 <component name="ToolWindowManager">
228   - <frame x="-8" y="-8" width="1936" height="1056" extended-state="6" />
229   - <editor active="true" />
  235 + <frame x="-1374" y="471" width="1382" height="784" extended-state="6" />
230 236 <layout>
231   - <window_info content_ui="combo" id="Project" order="0" sideWeight="0.69631237" visible="true" weight="0.19968387" />
  237 + <window_info content_ui="combo" id="Project" order="0" sideWeight="0.70153844" visible="true" weight="0.18377976" />
232 238 <window_info id="Structure" order="1" weight="0.25" />
233   - <window_info id="npm" order="2" sideWeight="0.30368763" side_tool="true" visible="true" weight="0.19968387" />
  239 + <window_info id="npm" order="2" sideWeight="0.29846153" side_tool="true" visible="true" weight="0.18377976" />
234 240 <window_info id="Favorites" order="3" side_tool="true" />
235 241 <window_info anchor="bottom" id="Message" order="0" />
236 242 <window_info anchor="bottom" id="Find" order="1" />
237   - <window_info anchor="bottom" id="Run" order="2" weight="0.3277635" />
238   - <window_info anchor="bottom" id="Debug" order="3" weight="0.39903265" />
  243 + <window_info anchor="bottom" id="Run" order="2" weight="0.37384614" />
  244 + <window_info anchor="bottom" id="Debug" order="3" weight="0.42307693" />
239 245 <window_info anchor="bottom" id="Cvs" order="4" weight="0.25" />
240 246 <window_info anchor="bottom" id="Inspection" order="5" weight="0.4" />
241 247 <window_info anchor="bottom" id="TODO" order="6" />
242 248 <window_info anchor="bottom" id="Docker" order="7" show_stripe_button="false" />
243 249 <window_info anchor="bottom" id="Version Control" order="8" />
244   - <window_info anchor="bottom" id="Terminal" order="9" />
  250 + <window_info anchor="bottom" id="Terminal" order="9" weight="0.23969631" />
245 251 <window_info anchor="bottom" id="Event Log" order="10" side_tool="true" />
246 252 <window_info anchor="bottom" id="Messages" order="11" />
247 253 <window_info anchor="right" id="Commander" order="0" weight="0.4" />
... ... @@ -256,6 +262,24 @@
256 262 <component name="VcsContentAnnotationSettings">
257 263 <option name="myLimit" value="2678400000" />
258 264 </component>
  265 + <component name="XDebuggerManager">
  266 + <breakpoint-manager>
  267 + <breakpoints>
  268 + <line-breakpoint enabled="true" type="javascript">
  269 + <url>file://$PROJECT_DIR$/api/routes/routes.js</url>
  270 + <line>49</line>
  271 + <properties lambdaOrdinal="-1" />
  272 + <option name="timeStamp" value="9" />
  273 + </line-breakpoint>
  274 + <line-breakpoint enabled="true" type="javascript">
  275 + <url>file://$PROJECT_DIR$/api/routes/routes.js</url>
  276 + <line>48</line>
  277 + <properties lambdaOrdinal="-1" />
  278 + <option name="timeStamp" value="10" />
  279 + </line-breakpoint>
  280 + </breakpoints>
  281 + </breakpoint-manager>
  282 + </component>
259 283 <component name="editorHistoryManager">
260 284 <entry file="file://$PROJECT_DIR$/node_modules/cassandra-driver/lib/requests.js">
261 285 <provider selected="true" editor-type-id="text-editor">
... ... @@ -264,17 +288,24 @@
264 288 </state>
265 289 </provider>
266 290 </entry>
267   - <entry file="file://$PROJECT_DIR$/api/routes/routes.js">
  291 + <entry file="file://$PROJECT_DIR$/package.json">
268 292 <provider selected="true" editor-type-id="text-editor">
269   - <state relative-caret-position="415">
270   - <caret line="357" column="50" selection-start-line="357" selection-start-column="50" selection-end-line="357" selection-end-column="50" />
  293 + <state relative-caret-position="120">
  294 + <caret line="8" column="38" selection-start-line="8" selection-start-column="38" selection-end-line="8" selection-end-column="38" />
271 295 </state>
272 296 </provider>
273 297 </entry>
274   - <entry file="file://$PROJECT_DIR$/package.json">
  298 + <entry file="file://$PROJECT_DIR$/node_modules/password-hash/lib/password-hash.js">
  299 + <provider selected="true" editor-type-id="text-editor">
  300 + <state relative-caret-position="161">
  301 + <caret line="54" column="30" lean-forward="true" selection-start-line="54" selection-start-column="30" selection-end-line="54" selection-end-column="30" />
  302 + </state>
  303 + </provider>
  304 + </entry>
  305 + <entry file="file://$PROJECT_DIR$/api/routes/routes.js">
275 306 <provider selected="true" editor-type-id="text-editor">
276   - <state relative-caret-position="153">
277   - <caret line="9" column="4" selection-start-line="9" selection-start-column="4" selection-end-line="9" selection-end-column="4" />
  307 + <state relative-caret-position="173">
  308 + <caret line="55" column="62" selection-start-line="55" selection-start-column="62" selection-end-line="55" selection-end-column="62" />
278 309 </state>
279 310 </provider>
280 311 </entry>
... ...
restApi/api/routes/routes.js
... ... @@ -5,24 +5,76 @@ const Activity = require(&quot;../modules/activity.js&quot;);
5 5  
6 6 const uuid = require('uuid');
7 7 var cassandra = require("cassandra-driver");
  8 +var passwordHash = require('password-hash');
  9 +var byteRandomizer = require('randombytes');
  10 +var sha256 = require('sha256');
8 11  
9 12 var db = setupDatabase('127.0.0.1');
10 13  
  14 +function insertToken(username, token) {
  15 + var params = [username, token];
  16 + db.execute("INSERT INTO risk.keys (user, apitoken) " +
  17 + "VALUES (?,?)",
  18 + params,
  19 + { prepare : true },
  20 + function (error) {
  21 + if (error) console.log("Unable to insert token\n" + error);
  22 + }
  23 + );
  24 +}
  25 +
11 26 var appRouter = function(app) {
12 27  
13 28 //Root endpoint (http://localhost:3000)
14 29 app.get("/", function(req, res) {
15   - res.send("Evaluation API by Ali, Kristin and Anna is up and running...");
  30 + res.send("Evaluation API by Ali and Kristin is up and running...");
16 31 });
17 32  
  33 + app.post("/login", function (req, response) {
  34 + if (!req.body.username || !req.body.password) {
  35 + console.log("Missing params");
  36 + return response.status(400).send("Bad Request");
  37 + }
  38 +
  39 + var params = [req.body.username];
  40 + db.execute("SELECT passwordhash FROM risk.user WHERE username = ?", params, { prepare : true }, function (error, result) {
  41 + if (error) {
  42 + console.log("Wrong username or password\n" + error);
  43 + return response.status(403).send("Wrong username or password");
  44 + } else {
  45 + console.log("User found");
  46 +
  47 + var token = "";
  48 +
  49 + byteRandomizer(255 - req.body.username.length, function (err, res) {
  50 + token = sha256(req.body.username + res);
  51 +
  52 + insertToken(req.body.username, token);
  53 +
  54 + if (passwordHash.verify(req.body.password, result.rows[0].get(0))) {
  55 + console.log("Password for " + req.body.username + " accepted");
  56 + return response.status(202).send(token);
  57 + } else {
  58 + console.log("Password for " + req.body.username + " denied");
  59 + return response.status(403).send("Wrong username or password");
  60 + }
  61 + });
  62 + }
  63 + });
  64 +
  65 + });
18 66  
19 67 /**
20 68 * Get incident by id endpoint (a get request at http://localhost:3000/incident/1 will return incident with id 1)
21 69 */
22 70 app.get("/incident/:id", function (req, res) {
  71 + if (!checkForAuthorizedUser(req.body.token)) {
  72 + return res.status(401).send("Unauthorized user")
  73 + }
  74 +
23 75 if (!req.params.id) {
24 76 logEndpoint("get /incident/{id}", null, "ID missing");
25   - return req.status(400).send("No id entered");
  77 + return res.status(400).send("No id entered");
26 78 }
27 79  
28 80 const params = [req.params.id];
... ... @@ -52,6 +104,9 @@ var appRouter = function(app) {
52 104 * See all incidents (a get request at http://localhost:3000/incident will return all incidents)
53 105 */
54 106 app.get("/incident", function (req, res) {
  107 + if (!checkForAuthorizedUser(req.body.token)) {
  108 + return res.status(401).send("Unauthorized user")
  109 + }
55 110  
56 111 db.execute('SELECT * ' +
57 112 'FROM risk.incident',
... ... @@ -77,6 +132,9 @@ var appRouter = function(app) {
77 132 * Add a new incident (a post request at http://localhost:3000/incident - with an "x-www-form-urlencoded" body of params)
78 133 */
79 134 app.post("/incident", function(req, res) {
  135 + if (!checkForAuthorizedUser(req.body.token)) {
  136 + return res.status(401).send("Unauthorized user")
  137 + }
80 138  
81 139 // All these parameters must exist in the body with the exact name for this method to work
82 140 if(!req.body.date || !req.body.location || !req.body.title || !req.body.description || !req.body.associatedEval) {
... ... @@ -101,6 +159,9 @@ var appRouter = function(app) {
101 159 * Update an incident (a patch request at http://localhost:3000/incident/{id} will update the incident with the params passed in the request body)
102 160 */
103 161 app.patch("/incident/:id", function (req, res) {
  162 + if (!checkForAuthorizedUser(req.body.token)) {
  163 + return res.status(401).send("Unauthorized user")
  164 + }
104 165  
105 166 if (!req.params.id) {
106 167 logEndpoint("patch /incident", null, "ID missing");
... ... @@ -133,6 +194,10 @@ var appRouter = function(app) {
133 194 * Delete an incident (a delete request at http://localhost:3000/incident/{id} should delete incident with the id passed in)
134 195 */
135 196 app.delete("/incident/:id", function (req, res) {
  197 + if (!checkForAuthorizedUser(req.body.token)) {
  198 + return res.status(401).send("Unauthorized user")
  199 + }
  200 +
136 201 if (!req.params.id) {
137 202 logEndpoint("delete /incident", null, "ID missing");
138 203 return res.status(400).send("Missing id");
... ... @@ -159,6 +224,10 @@ var appRouter = function(app) {
159 224 * See an evaluation with id x
160 225 */
161 226 app.get("/evaluation/:id", function (req, res) {
  227 + if (!checkForAuthorizedUser(req.body.token)) {
  228 + return res.status(401).send("Unauthorized user")
  229 + }
  230 +
162 231 if (!req.params.id) {
163 232 logEndpoint("get /evaluation/{id}", null, "ID missing");
164 233 return req.status(400).send("No id entered");
... ... @@ -192,6 +261,9 @@ var appRouter = function(app) {
192 261 * See all evaluations
193 262 */
194 263 app.get("/evaluation", function (req, res) {
  264 + if (!checkForAuthorizedUser(req.body.token)) {
  265 + return res.status(401).send("Unauthorized user")
  266 + }
195 267  
196 268 db.execute('SELECT * ' +
197 269 'FROM risk.evaluation',
... ... @@ -217,6 +289,10 @@ var appRouter = function(app) {
217 289 * Add a new evaluation
218 290 */
219 291 app.post("/evaluation", function(req, res) {
  292 + if (!checkForAuthorizedUser(req.body.token)) {
  293 + return res.status(401).send("Unauthorized user")
  294 + }
  295 +
220 296 if(!req.body.title || !req.body.outcome || !req.body.measures || !req.body.consequence || !req.body.probability || !req.body.associatedActivity) {
221 297 logEndpoint("post /evaluation/", null, "Missing params in body");
222 298 return res.status(400).send("Missing params");
... ... @@ -241,6 +317,10 @@ var appRouter = function(app) {
241 317 */
242 318  
243 319 app.delete("/evaluation/:id", function (req, res) {
  320 + if (!checkForAuthorizedUser(req.body.token)) {
  321 + return res.status(401).send("Unauthorized user")
  322 + }
  323 +
244 324 if (!req.params.id) {
245 325 logEndpoint("delete /evaluation", null, "ID missing");
246 326 return res.status(400).send("Missing id");
... ... @@ -267,6 +347,10 @@ var appRouter = function(app) {
267 347 * See an activity with id x
268 348 */
269 349 app.get("/activity/:id", function (req, res) {
  350 + if (!checkForAuthorizedUser(req.body.token)) {
  351 + return res.status(401).send("Unauthorized user")
  352 + }
  353 +
270 354 if (!req.params.id) {
271 355 logEndpoint("get /activity/{id}", null, "ID missing");
272 356 return req.status(400).send("No id entered");
... ... @@ -299,6 +383,9 @@ var appRouter = function(app) {
299 383 * See all activities
300 384 */
301 385 app.get("/activity", function (req, res) {
  386 + if (!checkForAuthorizedUser(req.body.token)) {
  387 + return res.status(401).send("Unauthorized user")
  388 + }
302 389  
303 390 db.execute('SELECT * ' +
304 391 'FROM risk.activity',
... ... @@ -348,11 +435,22 @@ function setupTables(db) {
348 435 if (err) console.log("Failed to create keyspace. Error: " + err);
349 436  
350 437 db.execute("CREATE TABLE risk.incident(id uuid, date date, location text, title text, description text, associatedEval uuid, PRIMARY KEY(id));", function (err) {
351   - if (err) console.log("Failed to create table incident.\n" + err)
  438 + if (err) console.log("Failed to create table incident.\n" + err);
  439 + });
  440 +
  441 + db.execute("CREATE TABLE risk.user(username text, passwordHash text, name text, groupnumber int, PRIMARY KEY(username));", function (err) {
  442 + if (err) console.log("Failed to create table user.\n" + err);
  443 + else{
  444 + insertUser(db, "test1", "123456789", "test testesen", 1);
  445 + }
  446 + });
  447 +
  448 + db.execute("CREATE TABLE risk.keys(user text, apitoken text, PRIMARY KEY(user));", function (err) {
  449 + if (err) console.log("Failed to create table keys.\n" + err);
352 450 });
353 451  
354 452 db.execute("CREATE TABLE risk.evaluation(id uuid, title text, outcome text, measures text, consequence int, probability int, associatedActivity uuid, PRIMARY KEY(id));", function (err) {
355   - if (err) console.log("Failed to create table evaluation.\n" + err)
  453 + if (err) console.log("Failed to create table evaluation.\n" + err);
356 454 });
357 455  
358 456 db.execute("CREATE TABLE risk.activity(id uuid, title text, PRIMARY KEY(id));", function (err) {
... ... @@ -367,6 +465,25 @@ function setupTables(db) {
367 465 );
368 466 }
369 467  
  468 +function checkForAuthorizedUser(token) {
  469 + const params = [token];
  470 + db.execute("SELECT user FROM keys WHERE apitoken = ?;",
  471 + function (err, result) {
  472 + if(err) {
  473 + console.log("Failed to autorize API token");
  474 + return false;
  475 + } else {
  476 + if (result.rows.length != 0) {
  477 + console.log("Token successfully authorized");
  478 + return result.rows[0];
  479 + } else {