11package org.digma.intellij.plugin.common
22
33import com.intellij.openapi.components.service
4+ import org.apache.commons.codec.digest.DigestUtils
45import org.digma.intellij.plugin.persistence.PersistenceService
6+ import java.net.NetworkInterface
7+ import java.util.UUID
58
69object UniqueGeneratedUserId {
710
811 val userId: String
912 val isDevUser: Boolean
1013
1114 init {
12- val hostname = CommonUtils .getLocalHostname()
1315 if (System .getenv(" devenv" ) == " digma" ) {
14- userId = hostname
16+ userId = CommonUtils .getLocalHostname()
1517 isDevUser = true
1618 } else {
1719 if (service<PersistenceService >().getUserId() == null ) {
18- service<PersistenceService >().setUserId(Integer .toHexString(hostname.hashCode() ))
20+ service<PersistenceService >().setUserId(generateUniqueUserId( ))
1921 }
2022 userId = service<PersistenceService >().getUserId()!!
2123 isDevUser = false
2224 }
2325 }
26+ }
27+
28+
29+ // this method is outside the class so that it can be tested,UniqueGeneratedUserId can not be instantiated in regular unit tests
30+ fun generateUniqueUserId (): String {
31+ try {
32+ val userName = System .getProperty(" user.name" )
33+ val userHome = System .getProperty(" user.home" )
34+ val osName = System .getProperty(" os.name" )
35+ val osArch = System .getProperty(" os.arch" )
36+ // MUST BE SORTED
37+ val ni = NetworkInterface .networkInterfaces().toList().mapNotNull { it.hardwareAddress }.map { macAddressToString(it) }.sorted()
38+ .joinToString(" -" )
39+ val baseString = userName + userHome + osName + osArch + ni
40+ return DigestUtils .sha1Hex(baseString)
41+ } catch (e: Throwable ) {
42+ return DigestUtils .sha1Hex(UUID .randomUUID().toString())
43+ }
44+ }
45+
46+
47+ private fun macAddressToString (hardwareAddress : ByteArray? ): String {
48+
49+ if (hardwareAddress == null ) {
50+ return " "
51+ }
52+
53+ val sb = StringBuilder ()
54+ for (i in hardwareAddress.indices) {
55+ sb.append(java.lang.String .format(" %02X%s" , hardwareAddress[i], if ((i < hardwareAddress.size - 1 )) " -" else " " ))
56+ }
57+ return sb.toString()
2458}
0 commit comments