2021-10-01 09:09:20 +00:00
using Newtonsoft.Json ;
using Newtonsoft.Json.Converters ;
using System ;
using System.Collections.Generic ;
using System.Globalization ;
using System.IO ;
using System.Linq ;
using System.Net ;
using System.Net.Http ;
using System.Text ;
using System.Threading.Tasks ;
using System.Web.Http ;
2022-09-23 11:52:57 +00:00
using Xylem.Common.Logic.ServiceCore ;
2021-10-01 09:09:20 +00:00
namespace Xylem.Common.Service.MeterProcessState.Controllers
{
[RoutePrefix("api/OldPassword")]
public class OldPasswordController : ApiController
{
public static class GlobalConfig
{
public static Lazy < String > connectionString = new Lazy < String > ( ( )
= >
System . Configuration . ConfigurationManager . ConnectionStrings [ "default" ] . ConnectionString
) ;
}
[Route("SetPassword"), HttpGet]
2022-10-19 10:58:08 +00:00
public async Task < HttpResponseMessage > SetPassword ( String PcbId , String password , Boolean keepOldPw = false )
2021-10-01 09:09:20 +00:00
{
try
{
using ( var dataAccess = new SqlDataAccess ( GlobalConfig . connectionString . Value ) )
{
StringBuilder sb = new StringBuilder ( ) ;
if ( keepOldPw )
{
sb . AppendLine (
$"update auftrag.dbo.Genesis_PcbPassword set KitronSkeletonKey = [password] , [password] ='{password}' where PcbId='{PcbId}'" ) ;
}
else
{
sb . AppendLine (
$"Insert into dbo.Genesis_PcbPassword(PcbId, [password]) values('{PcbId}', '{password}')" ) ;
}
var dt = dataAccess . ExecuteQuery ( sb . ToString ( ) ) ;
}
return Request . CreateResponse ( HttpStatusCode . OK , await Task . Run ( ( ) = > { return "store" ; } ) ) ;
}
catch ( Exception ex )
{
return Request . CreateResponse ( HttpStatusCode . ExpectationFailed , ex ) ;
}
}
[Route("GetPassword")]
public async Task < HttpResponseMessage > GetPassword ( String PcbId )
{
try
{
var returnPw = "Not assigned" ;
using ( var dataAccess = new SqlDataAccess ( GlobalConfig . connectionString . Value ) )
{
var dt = dataAccess . ExecuteQuery ( $"select [password] , [isLocked],[KeySetId] ,[orderNumber],[radioAdress] from dbo.Genesis_PcbPassword where PcbId like '{PcbId}'" ) ;
foreach ( var item in dt . Select ( ) )
{
returnPw = item [ "password" ] . ToString ( ) ;
2022-10-19 10:58:08 +00:00
if ( ! ( Boolean ) item [ "isLocked" ] )
2021-10-01 09:09:20 +00:00
{
return Request . CreateResponse ( HttpStatusCode . OK , await Task . Run ( ( ) = > { return returnPw ; } ) ) ;
}
return Request . CreateResponse ( HttpStatusCode . OK , await Task . Run ( ( ) = > { return returnPw ; } ) ) ;
//if (string.IsNullOrEmpty(item["KeySetId"].ToString()))
//{
// return Request.CreateResponse(HttpStatusCode.InternalServerError, "no key set stored");
//}
//if (!Request.Headers.Contains("X-Node-Token"))
//{
// return Request.CreateResponse(HttpStatusCode.Forbidden, "Token is required for locked meter");
//}
//var Url = $"https://nodes.sms-esaap.com:8081/api/v3/custom/keysetkeys?orderNumber={item["orderNumber"].ToString()}&radioAdress={item["password"].ToString()}";
//var http = (HttpWebRequest)WebRequest.Create(Url);
//http.Headers.Add("Cache-Control", "no-cache");
//http.Headers.Add("X-Node-Token", Request.Headers.GetValues("X-Node-Token").First());
//Request.Headers.["X-Node-Token"]
//http.Headers.Add()
}
}
throw new Exception ( "blub" ) ;
}
catch ( Exception ex )
{
return Request . CreateResponse ( HttpStatusCode . InternalServerError , ex . ToString ( ) + "<br >" + ex . InnerException . ToString ( ) ) ;
}
}
public class MeterPasswordContainer
{
public Int64 ? orderNumber = null ;
public Int64 ? radioAdress = null ;
2022-10-19 10:58:08 +00:00
public String Skeleton = "" ;
public List < Byte [ ] > listOfHashes = new List < Byte [ ] > ( ) ;
public List < Byte [ ] > listOfPasswords = new List < Byte [ ] > ( ) ;
2021-10-01 09:09:20 +00:00
2022-10-19 10:58:08 +00:00
public String KeySetId { get ; internal set ; }
2021-10-01 09:09:20 +00:00
}
2022-10-19 10:58:08 +00:00
private MeterPw getKeys ( String Token , String orderNumber , String radioAdress )
2021-10-01 09:09:20 +00:00
{
ServicePointManager . ServerCertificateValidationCallback + = ( sender , certificate , chain , sslPolicyErrors ) = >
{
return true ;
} ;
//todo: amis haben keine radio adresse (pcbid)
var Url = $"https://nodes.sms-esaap.com:8081/api/v3/custom/keysetkeys?orderNumber={orderNumber}&radioAdress={radioAdress}" ;
var http = ( HttpWebRequest ) WebRequest . Create ( Url ) ;
http . Headers . Add ( "Cache-Control" , "no-cache" ) ;
//todo: X-noed-Token
http . Headers . Add ( "X-Node-Token" , "d5b8c0b2-81f6-4421-80d0-44eb2093e616" ) ;
try
{
var response = ( HttpWebResponse ) http . GetResponse ( ) ;
var responseStream = response . GetResponseStream ( ) ;
if ( responseStream = = null )
{
throw new InvalidOperationException ( ) ;
}
if ( response . StatusCode ! = HttpStatusCode . OK )
{
throw new ApplicationException ( "Unable to get keys from server" ) ;
}
using ( var sr = new StreamReader ( responseStream ) )
{
var responseJson = sr . ReadToEnd ( ) ;
responseJson = responseJson . Trim ( '"' ) ;
return MeterPw . FromJson ( responseJson ) ;
}
}
catch ( Exception ex )
{
throw new ApplicationException ( "Fatal exception while getting keys from server" , ex ) ;
}
}
[Route("GetPasswordHashFileContent")]
public async Task < HttpResponseMessage > GetPasswordHashFileContent ( String PcbId )
{
try
{
2022-10-19 10:58:08 +00:00
var listOfHashes = new List < Byte [ ] > ( ) ;
2021-10-01 09:09:20 +00:00
var sbOutPut = new StringBuilder ( ) ;
var sbQuery = new StringBuilder ( ) ;
sbQuery . AppendLine ( $" SELECT " ) ;
sbQuery . AppendLine ( $" [Seriennummer] " ) ;
sbQuery . AppendLine ( $" ,mps.MapPcbIdToSerialNumber_PcbId " ) ;
sbQuery . AppendLine ( $" ,[Adresse] " ) ;
sbQuery . AppendLine ( $" ,AuftragPosSNr.AuftragNr " ) ;
sbQuery . AppendLine ( $" ,Auftrag.FertigungsauftragNr " ) ;
sbQuery . AppendLine ( $" ,[GeschlossenDatum] " ) ;
sbQuery . AppendLine ( $" ,[Vergabe_am] " ) ;
sbQuery . AppendLine ( $" ,passwordtbl.KeySetId " ) ;
sbQuery . AppendLine ( $" ,passwordtbl.orderNumber " ) ;
sbQuery . AppendLine ( $" ,passwordtbl.Password as Skeleton " ) ;
sbQuery . AppendLine ( $" ,passwordtbl.ProcessorID as ProcessorUid " ) ;
sbQuery . AppendLine ( $" FROM [Auftrag].[dbo].[Genesis_Meter] meter " ) ;
sbQuery . AppendLine ( $" inner join MapPcbIdToSerialNumber mps" +
$" on mps.MapPcbIdToSerialNumber_SerialNumber = meter.Seriennummer and mps.MapPcbIdToSerialNumber_Deleted = 0 " ) ;
sbQuery . AppendLine ( $" inner join[Auftrag].[dbo].[AuftragPositionSerienNr] AuftragPosSNr " +
$" on AuftragPosSNr.SerienNr = meter.Seriennummer and [Pruefgangnr] = 0 " ) ;
sbQuery . AppendLine ( $" inner join[Auftrag].[dbo].[AuftragPosition] Auftrag" +
$" on Auftrag.AuftragNr = AuftragPosSNr.AuftragNr and AuftragPosSNr.PositionNr = Auftrag.PositionNr " ) ;
sbQuery . AppendLine ( $" left outer join[dbo].[Genesis_PcbPassword] passwordtbl" +
$" on passwordtbl.PcbId = mps.MapPcbIdToSerialNumber_PcbId " ) ;
sbQuery . AppendLine ( $" where mps.MapPcbIdToSerialNumber_PcbId = '{PcbId}' " ) ;
var result = new MeterPasswordContainer ( ) ;
using ( var dataAccess = new SqlDataAccess ( GlobalConfig . connectionString . Value ) )
{
var dt = dataAccess . ExecuteQuery ( sbQuery . ToString ( ) ) ;
foreach ( var item in dt . Select ( ) )
{
result . orderNumber = ( Int32 ) item [ "FertigungsauftragNr" ] ;
result . radioAdress = ( Int64 ) item [ "Adresse" ] ;
2022-10-19 10:58:08 +00:00
result . Skeleton = ( String ) item [ "Skeleton" ] ;
2021-10-01 09:09:20 +00:00
if ( item [ "KeySetId" ] . GetType ( ) ! = typeof ( System . DBNull ) )
{
2022-10-19 10:58:08 +00:00
result . KeySetId = ( String ) item [ "KeySetId" ] ;
2021-10-01 09:09:20 +00:00
}
}
}
if ( ! result . orderNumber . HasValue | | ! result . radioAdress . HasValue )
{
return Request . CreateResponse ( HttpStatusCode . InternalServerError , "PcbId not found" ) ;
}
if ( string . IsNullOrEmpty ( result . KeySetId ) )
{
result . KeySetId = CreateKeySet ( 7 ) ;
//mapp keyset
MapKeySet ( result . KeySetId , result . orderNumber . Value , result . radioAdress . Value ) ;
using ( var dataAccess = new SqlDataAccess ( GlobalConfig . connectionString . Value ) )
{
var dt = dataAccess . ExecuteQuery (
$"update auftrag.[dbo].[Genesis_PcbPassword] set KeySetId = '{result.KeySetId}' where PcbId = '{PcbId}'; select * from auftrag.[dbo].[Genesis_PcbPassword] where PcbId = '{PcbId}'" ) ;
}
}
var passwords = getKeys ( "" , result . orderNumber . Value . ToString ( ) , result . radioAdress . Value . ToString ( ) ) ;
passwords . Keys . Insert ( 2 , new Key ( ) { Index = 2 , KeyKey = result . Skeleton } ) ;
foreach ( var keyLVL in passwords . Keys )
{
using ( System . Security . Cryptography . SHA1Managed sha1 = new System . Security . Cryptography . SHA1Managed ( ) )
{
var rawKey = keyLVL . KeyKey ;
if ( rawKey . Length > 12 )
{
rawKey = rawKey . Substring ( 0 , 12 ) ;
}
if ( result . listOfPasswords . Count < = 7 )
{
result . listOfPasswords . Add ( Encoding . UTF8 . GetBytes ( rawKey ) ) ;
var hash = sha1 . ComputeHash ( Encoding . UTF8 . GetBytes ( rawKey ) ) ;
result . listOfHashes . Add ( hash ) ;
}
}
}
return Request . CreateResponse ( HttpStatusCode . OK , await Task . Run ( ( ) = >
{
return result ;
} ) ) ;
//if (resultBinary)
//{
// return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() =>
// {
// return listOfHashes;
// }));
//}
//else
//{
// return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() =>
// {
// var sbResult = new StringBuilder();
// foreach (var hashResult in listOfHashes)
// {
// foreach (var b in hashResult)
// {
// sbResult.Append(b.ToString("X2"));
// }
// sbResult.AppendLine();
// }
// return sbResult.ToString();
// }));
//}
}
catch ( Exception ex )
{
return Request . CreateResponse ( HttpStatusCode . ExpectationFailed , ex . ToString ( ) + "<br >" + ex . InnerException . ToString ( ) ) ;
}
}
2022-10-19 10:58:08 +00:00
private String MapKeySet ( String KeySetID , Int64 orderNumber , Int64 radioAdress )
2021-10-01 09:09:20 +00:00
{
var Url = $"https://nodes.sms-esaap.com:8081/api/v3/custom/keysets/devices" ;
var http = ( HttpWebRequest ) WebRequest . Create ( Url ) ;
http . Headers . Add ( "Cache-Control" , "no-cache" ) ;
http . Headers . Add ( "X-Node-Token" , "d5b8c0b2-81f6-4421-80d0-44eb2093e616" ) ;
2022-10-19 10:58:08 +00:00
String postData = $"[{{\" setId \ ":\"{KeySetID}\", \"orderNumber\":\"{orderNumber}\", \"radioAdress\":\"{radioAdress}\"}}]" ;
2021-10-01 09:09:20 +00:00
ASCIIEncoding encoding = new ASCIIEncoding ( ) ;
2022-10-19 10:58:08 +00:00
Byte [ ] byte1 = encoding . GetBytes ( postData ) ;
2021-10-01 09:09:20 +00:00
// Set the content type of the data being posted.
http . ContentType = "application/json; charset=utf-8" ;
http . Method = "POST" ;
// Set the content length of the string being posted.
http . ContentLength = byte1 . Length ;
Stream newStream = http . GetRequestStream ( ) ;
newStream . Write ( byte1 , 0 , byte1 . Length ) ;
newStream . Close ( ) ;
var response = ( HttpWebResponse ) http . GetResponse ( ) ;
var responseStream = response . GetResponseStream ( ) ;
if ( responseStream = = null )
{
throw new InvalidOperationException ( ) ;
}
if ( response . StatusCode ! = HttpStatusCode . OK )
{
}
using ( var sr = new StreamReader ( responseStream ) )
{
var responseJson = sr . ReadToEnd ( ) ;
responseJson = responseJson . Trim ( '"' ) ;
return responseJson . ToString ( ) ;
}
}
2022-10-19 10:58:08 +00:00
private String CreateKeySet ( Int32 CountKeys )
2021-10-01 09:09:20 +00:00
{
var Url = $"https://nodes.sms-esaap.com:8081/api/v3/custom/keysets" ;
var http = ( HttpWebRequest ) WebRequest . Create ( Url ) ;
http . Headers . Add ( "Cache-Control" , "no-cache" ) ;
http . Headers . Add ( "X-Node-Token" , "d5b8c0b2-81f6-4421-80d0-44eb2093e616" ) ;
2022-10-19 10:58:08 +00:00
String postData = $"{{\" setCount \ ": 1,\"keysPerSet\": {CountKeys} }}" ;
2021-10-01 09:09:20 +00:00
ASCIIEncoding encoding = new ASCIIEncoding ( ) ;
2022-10-19 10:58:08 +00:00
Byte [ ] byte1 = encoding . GetBytes ( postData ) ;
2021-10-01 09:09:20 +00:00
// Set the content type of the data being posted.
http . ContentType = "application/json; charset=utf-8" ;
http . Method = "POST" ;
// Set the content length of the string being posted.
http . ContentLength = byte1 . Length ;
Stream newStream = http . GetRequestStream ( ) ;
newStream . Write ( byte1 , 0 , byte1 . Length ) ;
newStream . Close ( ) ;
var response = ( HttpWebResponse ) http . GetResponse ( ) ;
var responseStream = response . GetResponseStream ( ) ;
if ( responseStream = = null )
{
throw new InvalidOperationException ( ) ;
}
if ( response . StatusCode ! = HttpStatusCode . OK )
{
}
using ( var sr = new StreamReader ( responseStream ) )
{
var responseJson = sr . ReadToEnd ( ) ;
responseJson = responseJson . Trim ( '"' ) ;
var res = MeterPw . ArrayFromJson ( responseJson ) ;
return res [ 0 ] . SetId . ToString ( ) ;
}
}
public partial class MeterPw
{
[JsonProperty("SetId")]
public Guid SetId { get ; set ; }
[JsonProperty("Keys")]
public List < Key > Keys { get ; set ; }
}
public partial class Key
{
[JsonProperty("Index")]
2022-10-19 10:58:08 +00:00
public Int64 Index { get ; set ; }
2021-10-01 09:09:20 +00:00
[JsonProperty("Key")]
2022-10-19 10:58:08 +00:00
public String KeyKey { get ; set ; }
2021-10-01 09:09:20 +00:00
}
public partial class MeterPw
{
public static MeterPw Empty ( ) = > new MeterPw ( ) { SetId = Guid . Empty , Keys = new List < Key > ( ) } ;
2022-10-19 10:58:08 +00:00
public static MeterPw FromJson ( String json ) = > JsonConvert . DeserializeObject < MeterPw > ( json , Converter . Settings ) ;
public static MeterPw [ ] ArrayFromJson ( String json ) = > JsonConvert . DeserializeObject < MeterPw [ ] > ( json , Converter . Settings ) ;
2021-10-01 09:09:20 +00:00
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling . Ignore ,
DateParseHandling = DateParseHandling . None ,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles . AssumeUniversal }
} ,
} ;
}
[Route("GetKeySetId")]
public async Task < HttpResponseMessage > GetKeySetId ( String PcbId )
{
try
{
var returnKeySetId = "Not assigned" ;
using ( var dataAccess = new SqlDataAccess ( GlobalConfig . connectionString . Value ) )
{
var dt = dataAccess . ExecuteQuery ( $"select [KeySetId] from dbo.Genesis_PcbPassword where PcbId like '{PcbId}'" ) ;
foreach ( var item in dt . Select ( ) )
{
returnKeySetId = item [ "KeySetId" ] . ToString ( ) ;
}
}
return Request . CreateResponse ( HttpStatusCode . OK , await Task . Run ( ( ) = > { return returnKeySetId ; } ) ) ;
}
catch ( Exception ex )
{
return Request . CreateResponse ( HttpStatusCode . ExpectationFailed , ex . ToString ( ) + "<br >" + ex . InnerException . ToString ( ) ) ;
}
}
}
}