-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathLoginService.cs
More file actions
91 lines (81 loc) · 2.97 KB
/
LoginService.cs
File metadata and controls
91 lines (81 loc) · 2.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using System.Globalization;
using Newtonsoft.Json.Linq;
using OtpNet;
using Contentstack.Management.Core.Http;
namespace Contentstack.Management.Core.Services.User
{
internal class LoginService : ContentstackService
{
#region Private
private readonly ICredentials _credentials;
private readonly string _token;
#endregion
#region Constructor
internal LoginService(JsonSerializer serializer, ICredentials credentials, string token = null, string mfaSecret = null): base(serializer)
{
this.HttpMethod = "POST";
this.ResourcePath = "user-session";
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
_credentials = credentials;
if (string.IsNullOrEmpty(token) && !string.IsNullOrEmpty(mfaSecret))
{
var secretBytes = Base32Encoding.ToBytes(mfaSecret);
var totp = new Totp(secretBytes);
_token = totp.ComputeTotp();
}
else
{
_token = token;
}
}
#endregion
public override void ContentBody()
{
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
var credential = _credentials as NetworkCredential;
JsonWriter writer = new JsonTextWriter(stringWriter);
writer.WriteStartObject();
writer.WritePropertyName("user");
writer.WriteStartObject();
writer.WritePropertyName("email");
writer.WriteValue(credential.UserName);
writer.WritePropertyName("password");
writer.WriteValue(credential.Password);
if (_token != null)
{
writer.WritePropertyName("tfa_token");
writer.WriteValue(_token);
}
writer.WriteEndObject();
writer.WriteEndObject();
string snippet = stringWriter.ToString();
this.ByteContent = System.Text.Encoding.UTF8.GetBytes(snippet);
}
}
public override void OnResponse(IResponse httpResponse, ContentstackClientOptions config)
{
if (httpResponse.IsSuccessStatusCode)
{
JObject jObject = httpResponse.OpenJObjectResponse();
var user = jObject.GetValue("user");
if (user != null && user.GetType() == typeof(JObject))
{
JObject userObj = (JObject)user;
var authtoken = userObj.GetValue("authtoken");
if (authtoken != null)
{
config.Authtoken = (string)authtoken;
}
}
}
}
}
}